如何将Linq扩展到SQL?
时间:2020-03-05 18:53:30 来源:igfitidea点击:
去年,Scott Guthrie表示,如果要对执行的SQL进行绝对控制,实际上可以覆盖LINQ to SQL所使用的原始SQL,但是我找不到描述可扩展性方法的文档。
我想将以下LINQ修改为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; } }
除此以外,使用某种类型的LINQ to SQL可扩展性。有任何想法吗?
解决方案
回答
DataContext x =新的DataContext;
//也许是这样?
var a = x.Where()。with()... etc
让我们对sql进行更精细的控制。
回答
我们想将表达式树转换为SQL ...我们需要实现自己的IQueryProvider
IQueryProvider参考
如何
MSDN如何
回答
更改基础提供程序并因此修改SQL的能力并未使LINQ to SQL最终切入。
回答
马特·沃伦(Matt Warren)的博客提供了我们所需的一切:
http://blogs.msdn.com/mattwar/