在已编译的LINQ查询中使用lambda Include方法

时间:2011-11-16 22:35:53

标签: c# linq-to-entities entity-framework-4.1 self-tracking-entities

我目前正在尝试通过预编译来优化程序中的一些LINQ查询。 其中一些查询广泛使用了预先加载;这是一个例子:

public static Func<DatabaseEntities, string, IQueryable<Employee>> GetAllByName =
              CompiledQuery.Compile<DatabaseEntities, string, IQueryable<Employee>
              ((context, name) => context.Employees
                     .Include(e => e.Email)
                     .Where(e => e.LastName == name));

使用示例:

var employees = GetAllByName(dbContext, "Bob").ToList();

不幸的是,尝试使用此操作会导致以下错误:

  

LINQ to Entities无法识别方法&#39; System.Linq.IQueryable [Employee] Include [Employee,Email](System.Linq.IQueryable [Employee],System.Linq.Expressions.Expression [System.Func] [员工,电子邮件]])&#39;方法,并且此方法无法转换为商店表达式。

我注意到正常的加载加载方法(Include(string))在预编译查询中运行正常。有没有办法使用lambda版本?

2 个答案:

答案 0 :(得分:2)

简而言之,没有。

您不能在预编译的linq语句/查询中使用lambda。

答案 1 :(得分:1)

您可以编辑代码预编译,例如:

public static Func<DatabaseEntities, string, IQueryable<Employee>> GetAllByName =
              CompiledQuery.Compile<DatabaseEntities, string, IQueryable<Employee>
              ((context, name) => context.Employees
                     .Include("Email")
                     .Where(e => e.LastName == name));