题
去年,斯科特·格思里 指出 “如果你想绝对控制执行的 SQL,你实际上可以覆盖 LINQ to SQL 使用的原始 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; } }
使用某种类型的 LINQ to SQL 扩展性,除了 这个. 。有任何想法吗?
解决方案
更改底层提供程序并因此修改 SQL 的能力并未最终成为 LINQ to SQL 的最终目标。
其他提示
马特·沃伦 (Matt Warren) 的博客拥有您所需的一切:
数据上下文 x = 新的数据上下文;
//也许是这样的?
var a = x.Where().with()...等
让您可以更好地控制 sql。
不隶属于 StackOverflow