你如何将Linq扩展到SQL?

时间:2008-09-15 13:41:40

标签: linq linq-to-sql

去年,Scott Guthrie stated“如果你想对所执行的SQL进行绝对控制,你实际上可以覆盖LINQ to SQL使用的原始SQL”,但我找不到描述可扩展性方法的文档。 / p>

我想修改以下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可扩展性,而不是this one。有什么想法吗?

4 个答案:

答案 0 :(得分:9)

更改底层提供程序并因此修改SQL的能力并未在LINQ to SQL中进行最终切割。

答案 1 :(得分:2)

Matt Warren的博客拥有您需要的一切:

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

答案 2 :(得分:1)

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

IQueryProvider Reference
How To

MSDN How To

答案 3 :(得分:0)

DataContext x = new DataContext;

//或许这样的事情?

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

让你对sql有更好的控制。