Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the lambda Include method in a compiled LINQ query

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?

like image 208
Lucas B Avatar asked Nov 16 '11 22:11

Lucas B


2 Answers

In short, no.

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

like image 106
one.beat.consumer Avatar answered Oct 13 '22 03:10

one.beat.consumer


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));
like image 45
Nguyễn Quốc Khánh Avatar answered Oct 13 '22 05:10

Nguyễn Quốc Khánh