2008-09-15 25 views
10

去年,斯科特·格思裏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等。有任何想法嗎?

回答

7

改變底層提供,因此修改能力SQL沒有在LINQ to SQL中做最後的裁剪。

0

DataContext的X =新的DataContext;

//像這樣的事情吧?

VAR一個= x.Where()與()...等

假設您有在SQL更精細的控制。

+0

即使這不工作,不`VAR一個= x.Where()...`意味着您已執行一個'選擇',因此有記錄,你不應該在第一個地方查詢? – IAbstract 2010-09-19 16:18:03

0

要轉換的表達式目錄樹到SQL ......你需要實現自己的IQueryProvider

IQueryProvider Reference
How To

MSDN How To

+1

似乎是社會需要以開放實現一個查詢提供了SQL表達式樹:-) – 2008-09-15 18:12:55

+0

實際上的加強,我想_extend_ LINQ到SQL的執行IQueryProvider ... – 2008-09-15 19:37:25