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?
In short, no.
You cannot use the lambda within a precompiled linq statement/query.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With