使用Func作为选择vs内联选择时sql之间的区别

时间:2013-06-19 21:15:40

标签: c# sql linq entity-framework

我试图理解为什么这两个语句的sql是不同的(区别似乎在于确定是否在select中添加SignedXml或使用case语句。但为什么?)。

myTable.Where(p => p.OwnerID.Equals(owner) && p.FolderID == folderId)
       .Select(source => new SignedNativeAnalysis
       {
          ID = source.ID,
          Name = source.Name,
          Created = source.Created,
          FolderID = source.FolderID,
          Locked = source.Locked,
          Modified = source.Modified,
          OwnerID = source.OwnerID,
          IsSigned = source.SignedXml != null
       });

生成如下内容:

exec sp_executesql N'SELECT 
[Extent1].[ID] AS [ID], 
[Extent1].[Name] AS [Name], 
[Extent1].[Created] AS [Created], 
[Extent1].[FolderID] AS [FolderID], 
[Extent1].[Locked] AS [Locked], 
[Extent1].[Modified] AS [Modified], 
[Extent1].[OwnerID] AS [OwnerID], 
CASE WHEN ([Extent1].[SignedXml] IS NOT NULL) THEN cast(1 as bit) WHEN ([Extent1].[SignedXml] IS NULL) THEN cast(0 as bit) END AS [C1]
FROM [dbo].[NativeAnalyses] AS [Extent1]
WHERE ([Extent1].[OwnerID] = @p__linq__0) AND ([Extent1].[FolderID] = @p__linq__1)',N'@p__linq__0 uniqueidentifier,@p__linq__1 

vs当我使用函数进行选择时:

myTable.Where(p => p.OwnerID.Equals(owner) && p.FolderID == folderId)
       .Select(Select);

和选择

private SignedNativeAnalysis Select(NativeAnalysis source)
{
      return new SignedNativeAnalysis
      {
        ID = source.ID,
        Name = source.Name,
        Created = source.Created,
        FolderID = source.FolderID,
        Locked = source.Locked,
        Modified = source.Modified,
        OwnerID = source.OwnerID,
        IsSigned = source.SignedXml != null
      };
}

生成如下内容:

exec sp_executesql N'SELECT 
[Extent1].[ID] AS [ID], 
[Extent1].[Name] AS [Name], 
[Extent1].[ModelXml] AS [ModelXml], 
[Extent1].[Created] AS [Created], 
[Extent1].[Modified] AS [Modified], 
[Extent1].[OwnerID] AS [OwnerID], 
[Extent1].[SignedXml] AS [SignedXml], 
[Extent1].[FolderID] AS [FolderID], 
[Extent1].[Locked] AS [Locked]
FROM [dbo].[NativeAnalyses] AS [Extent1]
WHERE ([Extent1].[OwnerID] = @p__linq__0) AND ([Extent1].[FolderID] = @p__linq__1)',N'@p__linq__0 uniqueidentifier,@p__linq__1 

SignedNativeAnalysis只用一个额外的属性继承了NativeAnalysis。

internal class SignedNativeAnalysis : NativeAnalysis
{
   public bool IsSigned { get; set; }
}

更新: 根据建议我尝试使用表达式来实现我想要的结果,但我得到了一个例外:

Expression<Func<NativeAnalysis, SignedNativeAnalysis>> signed = p => Select(p);
myTable.Where(p => p.OwnerID.Equals(owner) && p.FolderID == folderId)
       .Select(signed)
  

LINQ to Entities无法识别方法'SignedNativeAnalysis   选择(OverseerUI.EntityFramework.NativeAnalysis)'方法,这个   方法无法转换为商店表达式。

1 个答案:

答案 0 :(得分:2)

有一个技巧。实体框架选择不采用Func&lt; T,U&gt;。它需要表达式&lt; Func&lt; T,U&gt;&gt;。

因此,当您传递lambda时,编译器会将lambda转换为Expression,将其传递给EF,EF将表达式转换为SQL代码。

传递Func&lt; T,U&gt;没有办法将它转换为表达式。 Enumerable.Select扩展方法 - 采用普通的Func,而不是表达式 - 取而代之。所以EF执行第一部分,直到SQL中的Where。然后将结果传递给Linq to Object,在内存中执行投影。

你仍然可以做动态的东西,但你必须创建一个Expression的实例,而不是委托。