LINQ to SQL 支援三類可對應的函數:
[Function]、[Parameter])的方法。SqlMethods)。將函數拖曳至 O/R 設計器即可自動產生對應方法。
函數 TotalProductUnitPriceByCategory 回傳指定分類產品單價總和:
[Function(Name="dbo.TotalProductUnitPriceByCategory", IsComposable=true)]
public decimal? TotalProductUnitPriceByCategory([Parameter(DbType="Int")] int? categoryID) {
return (decimal?)this.ExecuteMethodCall(this, MethodInfo.GetCurrentMethod(), categoryID).ReturnValue;
}
查詢用法:
var q = from c in db.Categories
select new {
c.CategoryID,
TotalUnitPrice = db.TotalProductUnitPriceByCategory(c.CategoryID)
};
生成 SQL:SELECT [t0].[CategoryID], CONVERT(Decimal(29,4), [dbo].[TotalProductUnitPriceByCategory]([t0].[CategoryID])) AS [TotalUnitPrice] FROM [dbo].[Categories] AS [t0]
函數 MinUnitPriceByCategory 回傳分類最低單價:
var q = from p in db.Products
where p.UnitPrice == db.MinUnitPriceByCategory(p.CategoryID)
select p;
生成 SQL 將函數呼叫內嵌於 WHERE 子句。
函數 ProductsUnderThisUnitPrice(@price) 回傳價格低於參數的產品集合:
[Function(Name="dbo.ProductsUnderThisUnitPrice", IsComposable=true)]
public IQueryable<ProductsUnderThisUnitPriceResult> ProductsUnderThisUnitPrice([Parameter(DbType="Money")] decimal? price) {
return this.CreateMethodCallQuery<ProductsUnderThisUnitPriceResult>(this, MethodInfo.GetCurrentMethod(), price);
}
查詢並篩選未停產產品:
var q = from p in db.ProductsUnderThisUnitPrice(10.25M)
where !(p.Discontinued ?? false)
select p;
生成 SQL 直接查詢函數回傳的資料表。
var q = from c in db.Categories
join p in db.ProductsUnderThisUnitPrice(8.50M) on c.CategoryID equals p.CategoryID into prods
from p in prods
select new { c.CategoryID, c.CategoryName, p.ProductName, p.UnitPrice };
生成 SQL 使用 CROSS JOIN 搭配 WHERE 實現聯接邏輯。