Using the lambda Include method in a compiled LINQ query
Asked Answered
S

2

11

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?

Surgery answered 16/11, 2011 at 22:35 Comment(0)
R
2

In short, no.

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

Radioelement answered 13/12, 2011 at 1:31 Comment(0)
M
1

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));
Manipulate answered 20/11, 2011 at 18:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.