首页 / 知识

如何将Linq扩展到SQL?

2023-04-15 08:46:00

如何将Linq扩展到SQL?

How do you extend Linq to SQL?

去年,斯科特·格思里(Scott Guthrie)说:"如果您想对执行的SQL进行绝对控制,那么您实际上可以覆盖LINQ to SQL使用的原始SQL",但是我找不到描述可扩展性方法的文档。

我想将以下LINQ修改为SQL查询:

1
2
3
4
5
6
7
8
using (NorthwindContext northwind = new NorthwindContext ()) {
    var q = from row in northwind.Customers
            let orderCount = row.Orders.Count ()
            select new {
                row.ContactName,
                orderCount
            };
}

这将导致以下TSQL:

1
2
3
4
5
6
SELECT [t0].[ContactName], (
    SELECT COUNT(*)
    FROM [dbo].[Orders] AS [t1]
    WHERE [t1].[CustomerID] = [t0].[CustomerID]
    ) AS [orderCount]
FROM [dbo].[Customers] AS [t0]

至:

1
2
3
4
5
6
7
8
9
10
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:

1
2
3
4
5
6
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))

使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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;
}

1
2
3
4
5
6
7
8
9
10
11
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)的博客提供了您所需的一切:

http://blogs.msdn.com/mattwar/


您想将表达式树转换为SQL ...您需要实现自己的IQueryProvider

IQueryProvider参考
如何

MSDN如何


DataContext x =新的DataContext;

//也许是这样?

var a = x.Where()。with()... etc

让我们对sql进行更好的控制。


覆盖执行控制描述

最新内容

相关内容

猜你喜欢