Linq表值函數(shù)詳細(xì)分析
Linq有很多值得學(xué)習(xí)的地方,這里我們主要介紹Linq表值函數(shù),包括介紹修改一下Discontinued屬性為可空的bool類型等方面。
使用用戶定義的Linq表值函數(shù)
Linq表值函數(shù)返回單個(gè)行集(與存儲(chǔ)過程不同,存儲(chǔ)過程可返回多個(gè)結(jié)果形狀)。由于Linq表值函數(shù)的返回類型為 Table,因此在 SQL 中可以使用表的任何地方均可以使用Linq表值函數(shù)。此外,您還可以完全像處理表那樣來處理Linq表值函數(shù)。
下面的 SQL 用戶定義函數(shù)顯式聲明其返回一個(gè) TABLE。因此,隱式定義了所返回的行集結(jié)構(gòu)。
- ALTER FUNCTION [dbo].[ProductsUnderThisUnitPrice]
- (@price Money
- )
- RETURNS TABLE
- AS
- RETURN
- SELECT *
- FROM Products as P
- Where p.UnitPrice < @price
拖到設(shè)計(jì)器中,LINQ to SQL 按如下方式映射此函數(shù):
- IsComposable=true)]
- public IQueryable<ProductsUnderThisUnitPriceResult>
- ProductsUnderThisUnitPrice([Parameter(DbType="Money")]
- System.Nullable<decimal> price)
- {
- return this.CreateMethodCallQuery
- <ProductsUnderThisUnitPriceResult>(this,
- ((MethodInfo)(MethodInfo.GetCurrentMethod())), price);
- }
這時(shí)我們小小的修改一下Discontinued屬性為可空的bool類型。
- private System.Nullable<bool> _Discontinued;
- public System.Nullable<bool> Discontinued
- {
- }
我們可以這樣調(diào)用使用了:
- 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]
以聯(lián)接方式使用用戶定義的Linq表值函數(shù)
我們利用上面的ProductsUnderThisUnitPrice用戶定義函數(shù),在 LINQ to SQL 中,調(diào)用如下:
- 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 代碼說明對(duì)此函數(shù)返回的表執(zhí)行聯(lián)接。
- 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]
【編輯推薦】