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

发布于 2024-12-16 13:05:36 字数 866 浏览 3 评论 0原文

我目前正在尝试通过预编译程序中的一些 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 无法识别方法“System.Linq.IQueryable[Employee] Include[Employee,Email] (System.Linq.IQueryable[Employee], System.Linq.Expressions.Expression[System.Func[Employee, Email]]) '方法,并且该方法不能转换为存储表达式。

我注意到预加载的正常方法(包含(字符串))在预编译查询中工作得很好。有没有办法也使用 lambda 版本?

I'm currently trying to optimize some of the LINQ queries in my program by precompiling them.
Some of these queries make extensive use of eager loading; here's an example of one:

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));

Example use:

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

Unfortunately, attempting to use this results in the following error:

LINQ to Entities does not recognize the method 'System.Linq.IQueryable[Employee] Include[Employee,Email] (System.Linq.IQueryable[Employee], System.Linq.Expressions.Expression[System.Func[Employee,Email]]) ' method, and this method cannot be translated into a store expression.

I've noticed that the normal method of eager loading (Include(string)) works fine within a precompiled query. Is there a way to use the lambda version as well?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我早已燃尽 2024-12-23 13:05:36

简而言之,不。

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

In short, no.

You cannot use the lambda within a precompiled linq statement/query.

浊酒尽余欢 2024-12-23 13:05:36

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

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));

You can edit code precompile such as:

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));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文