去年,斯科特·格思裏stated「實際上,你可以重寫,如果你想在執行的SQL絕對控制是LINQ to SQL中使用原始SQL」,但我不能找到一種描述方法,擴展文件。如何將Linq擴展到SQL?
我想修改下面的LINQ to SQL查詢:
using (NorthwindContext northwind = new NorthwindContext()) { var q = from row in northwind.Customers let orderCount = row.Orders.Count() select new { row.ContactName, orderCount }; }
導致下面的TSQL:
SELECT [t0].[ContactName], ( SELECT COUNT(*) FROM [dbo].[Orders] AS [t1] WHERE [t1].[CustomerID] = [t0].[CustomerID] ) AS [orderCount] FROM [dbo].[Customers] AS [t0]
要:
using (NorthwindContext northwind = new NorthwindContext()) { var q = from row in northwind.Customers.With ( TableHint.NoLock, TableHint.Index (0)) let orderCount = row.Orders.With ( TableHint.HoldLock).Count() select new { row.ContactName, orderCount }; }
其中會導致以下TSQL:
SELECT [t0].[ContactName], ( SELECT COUNT(*) FROM [dbo].[Orders] AS [t1] WITH (HOLDLOCK) WHERE [t1].[CustomerID] = [t0].[CustomerID] ) AS [orderCount] FROM [dbo].[Customers] AS [t0] WITH (NOLOCK, INDEX(0))
使用:
public static Table<TEntity> With<TEntity> ( this Table<TEntity> table, params TableHint[] args) where TEntity : class { //TODO: implement return table; } public static EntitySet<TEntity> With<TEntity> ( this EntitySet<TEntity> entitySet, params TableHint[] args) where TEntity : class { //TODO: implement return entitySet; }
而且
public class TableHint { //TODO: implement public static TableHint NoLock; public static TableHint HoldLock; public static TableHint Index (int id) { return null; } public static TableHint Index (string name) { return null; } }
使用到SQL擴展某些類型的LINQ,比this one等。有任何想法嗎?
即使這不工作,不`VAR一個= x.Where()...`意味着您已執行一個'選擇',因此有記錄,你不應該在第一個地方查詢? – IAbstract 2010-09-19 16:18:03