LINQ to SQL查询奇数实现

时间:2010-05-26 21:49:51

标签: linq linq-to-sql

前几天我遇到了一个有趣的Linq to SQL,呃功能。也许有人可以给出我对结果背后推理的合理解释。以下面的代码为例,它利用Linq to SQL DataContext中的AdventureWorks数据库设置。这是我单元测试的剪辑。从CustomerQuery_Test_01()和CustomerQuery_Test_02()调用返回的结果客户是相同的。但是,在SQLServer上执行的查询是不同的主要方式。 CustomerQuery_Test_01方法导致整个Customer表实现,对CustomerQuery_Test_02的调用只会导致单个客户具体化。生成的SQL查询位于此帖的底部。有人有充分的理由吗?对我来说,这是非常不直观的。

protected virtual Customer GetByPrimaryKey(Func<Customer, bool> keySelection)
{
    AdventureWorksDataContext context = new AdventureWorksDataContext();
    return (from r in context.Customers select r).SingleOrDefault(keySelection);
}

[TestMethod]
public void CustomerQuery_Test_01()
{
    Customer customer = GetByPrimaryKey(c => c.CustomerID == 2);
}

[TestMethod]
public void CustomerQuery_Test_02()
{
    AdventureWorksDataContext context = new AdventureWorksDataContext();
    Customer customer = (from r in context.Customers select r).SingleOrDefault(c => c.CustomerID == 2);
}

查询CustomerQuery_Test_01(注意缺少where子句)

SELECT [t0]。[CustomerID],[t0]。[NameStyle],[t0]。[Title],[t0]。[FirstName],[t0]。[MiddleName],[t0]。[LastName ],[t0]。[后缀],[t0]。[CompanyName],[t0]。[SalesPerson],[t0]。[EmailAddress],[t0]。[Phone],[t0]。[PasswordHash], [t0]。[PasswordSalt],[t0]。[rowguid],[t0]。[ModifiedDate] FROM [SalesLT]。[客户] AS [t0]

查询CustomerQuery_Test_02(注意where子句)

SELECT [t0]。[CustomerID],[t0]。[NameStyle],[t0]。[Title],[t0]。[FirstName],[t0]。[MiddleName],[t0]。[LastName ],[t0]。[后缀],[t0]。[CompanyName],[t0]。[SalesPerson],[t0]。[EmailAddress],[t0]。[Phone],[t0]。[PasswordHash], [t0]。[PasswordSalt],[t0]。[rowguid],[t0]。[ModifiedDate] FROM [SalesLT]。[客户] AS [t0] WHERE [t0]。[CustomerID] = @ p0

1 个答案:

答案 0 :(得分:1)

Func<Customer, bool> keySelection

那不是Expression<Func<Customer, bool>> ...编译器已解决Enumerable.Single而不是Queryable.Single