UDF 分標量值函數 (SVF)與表值函數 (TVF)。關鍵差異:UDF 支援內聯查詢(可在 SQL 陳述式中直接呼叫),SP 則不支援。LINQ to SQL 完整支援 UDF 內聯操作。
DBML 標記 IsComposable="true",生成方法回傳標量型別。可像普通方法呼叫,亦可內聯於 LINQ 查詢:
// SVF 範例:MinUnitPriceByCategory
var q = from p in db.Products
where p.UnitPrice == db.MinUnitPriceByCategory(p.CategoryID)
select p;
// 生成 SQL 直接呼叫 UDF:WHERE t0.UnitPrice = dbo.MinUnitPriceByCategory(t0.CategoryID)
// SELECT 子句呼叫
var q = from c in db.Categories
select new { c.CategoryID, Total = db.TotalProductUnitPriceByCategory(c.CategoryID) };
// OrderBy/GroupBy 皆可內聯
var q = from p in db.Products
group p by db.SVF(p.CategoryID) into g
order by db.SVF(g.Key)
select db.SVF(g.Key);
OR Designer/SqlMetal 不支援系統函數對應,可手動編寫 Partial 類別方法並標記 [Function(IsComposable=true)]:
[Function(Name="Var", IsComposable=true)]
public decimal? Var([Parameter(DbType="Money")] decimal? para) => ...
[Function(Name="NewID", IsComposable=true)]
public Guid NewID() => ...
// 使用:db.Products.OrderBy(p => db.NewID()).Take(10)
成功騙過 LINQ to SQL Runtime,直接呼叫 SQL 系統函數。
DBML 含 ElementType 定義回傳資料行。視為資料表使用,支援 from、join、union 等操作:
var q = from p in db.ProductsUnderThisUnitPrice(10.25m) select p;
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 };
LINQ to SQL 深度整合 UDF 內聯能力,特殊需求可手動對應系統函數,但非所有函數皆適用。