简体   繁体   中英

EF6 triggers new query on “Include”?

I am using EF6 and I noticed that when I "include" a child table in a query, EF triggers a new query for each one of the parent rows...is that ok? is there a way to avoid it and make it bring all the information with the main query only?

Here are my entities (not the exact code):

public class Contractor
{
   public int id { get; set;}
   public IEnumerable<ContractorEmployee> Employees;
}

public class ContractorEmployee
{
   public int id { get; set;}
   public int contractorId { get; set;}
}

And this is the query:

var fullContractors = dbContext.Contractors.Include("ContractorEmployee");

so if the fullContractors query retrieves 5 contractors, I see 5 extra queries in SQL bringing the contractor employees of each one of them.

Any way to avoid this and bring it all in the first "SELECT"???

Include method takes the name of the parameter as string it is recommended to use overloaded version of Include that takes Expression as parameter. You can have look at the overloaded version of extension method here .

So do it Either

var fullContractors = dbContext.Contractors.Include("Employees");

or go with Expression version like this:

var fullContractors = dbContext.Contractors.Include(d => d.Employees);

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