简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM