Linq表值函數詳細分析
Linq有很多值得學習的地方,這里我們主要介紹Linq表值函數,包括介紹修改一下Discontinued屬性為可空的bool類型等方面。
使用用戶定義的Linq表值函數
Linq表值函數返回單個行集(與存儲過程不同,存儲過程可返回多個結果形狀)。由于Linq表值函數的返回類型為 Table,因此在 SQL 中可以使用表的任何地方均可以使用Linq表值函數。此外,您還可以完全像處理表那樣來處理Linq表值函數。
下面的 SQL 用戶定義函數顯式聲明其返回一個 TABLE。因此,隱式定義了所返回的行集結構。
- ALTER FUNCTION [dbo].[ProductsUnderThisUnitPrice]
- (@price Money
- )
- RETURNS TABLE
- AS
- RETURN
- SELECT *
- FROM Products as P
- Where p.UnitPrice < @price
拖到設計器中,LINQ to SQL 按如下方式映射此函數:
- IsComposable=true)]
- public IQueryable<ProductsUnderThisUnitPriceResult>
- ProductsUnderThisUnitPrice([Parameter(DbType="Money")]
- System.Nullable<decimal> price)
- {
- return this.CreateMethodCallQuery
- <ProductsUnderThisUnitPriceResult>(this,
- ((MethodInfo)(MethodInfo.GetCurrentMethod())), price);
- }
這時我們小小的修改一下Discontinued屬性為可空的bool類型。
- private System.Nullable<bool> _Discontinued;
- public System.Nullable<bool> Discontinued
- {
- }
我們可以這樣調用使用了:
- var q = from p in db.ProductsUnderThisUnitPrice(10.25M)
- where !(p.Discontinued ?? false)
- select p;
其生成SQL語句如下:
- SELECT [t0].[ProductID], [t0].[ProductName], [t0].[SupplierID],
- [t0].[CategoryID], [t0].[QuantityPerUnit], [t0].[UnitPrice],
- [t0].[UnitsInStock], [t0].[UnitsOnOrder], [t0].[ReorderLevel],
- [t0].[Discontinued]
- FROM [dbo].[ProductsUnderThisUnitPrice](@p0) AS [t0]
- WHERE NOT ((COALESCE([t0].[Discontinued],@p1)) = 1)
- -- @p0: Input Money (Size = 0; Prec = 19; Scale = 4) [10.25]
- -- @p1: Input Int (Size = 0; Prec = 0; Scale = 0) [0]
以聯接方式使用用戶定義的Linq表值函數
我們利用上面的ProductsUnderThisUnitPrice用戶定義函數,在 LINQ to 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 代碼說明對此函數返回的表執行聯接。
- SELECT [t0].[CategoryID], [t0].[CategoryName],
- [t1].[ProductName], [t1].[UnitPrice]
- FROM [dbo].[Categories] AS [t0]
- CROSS JOIN [dbo].[ProductsUnderThisUnitPrice](@p0) AS [t1]
- WHERE ([t0].[CategoryID]) = [t1].[CategoryID]
- -- @p0: Input Money (Size = 0; Prec = 19; Scale = 4) [8.50]
【編輯推薦】