首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

LINQ to SQL 整合使用者定義函數:標量、表值與聯接應用

     編輯:關於.NET

使用者定義函數支援類型

LINQ to SQL 支援三類可對應的函數:

  1. 具備正確映射屬性([Function]、[Parameter])的方法。
  2. LINQ to SQL 專屬靜態 SQL 方法(SqlMethods)。
  3. .NET Framework 內建方法的轉譯支援。

將函數拖曳至 O/R 設計器即可自動產生對應方法。

範例資料庫:Northwind 內建函數

1. Select 中呼叫標量函數

函數 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]

2. Where 條件中使用標量函數

函數 MinUnitPriceByCategory 回傳分類最低單價:

var q = from p in db.Products
        where p.UnitPrice == db.MinUnitPriceByCategory(p.CategoryID)
        select p;

生成 SQL 將函數呼叫內嵌於 WHERE 子句。

3. 表值函數:當作資料表查詢

函數 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 直接查詢函數回傳的資料表。

4. 表值函數參與聯接

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 實現聯接邏輯。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved