I have a problem with EF6 when trying to optimize queries. Consider this class with one collection:
public class Client
{
... a lot of properties
public virtual List<Country> Countries { get; set; }
}
As you may know, with Lazy Loading, I have this n + 1 problem when EF tries to get all countries for each client.
I tried using Linq forecasts; eg:
return _dbContext.Clients
.Select(client => new
{
client,
client.Countries
}).ToList().Select(data =>
{
data.client.Countries = data.Countries;
return data.client;
}).ToList();
Here I use two choices: the first for Linq projection, so EF can create SQL, and the second for matching the result with the Client class. The reason for this is because I use the repository interface that returns List<Client>.
, , EF - Lazy Loading, ( n + 1). - :
public class Client
{
... a lot of properties
public List<Country> Countries { get; set; }
}
, . , Lazy Loading.
, "" EF , Linq. ? , - ? n + 1 , 1000 .
Edit
. , Include() , , ( , , , ):
public class Client
{
... a lot of properties
public virtual List<Country> Countries { get; set; }
public virtual List<Action> Actions { get; set; }
public virtual List<Investment> Investments { get; set; }
public User LastUpdatedBy {
get {
if(Actions != null) {
return Actions.Last();
}
}
}
}
, (Count()), Include() . , ,
return _dbContext.Clients
.Select(client => new
{
client,
client.Countries,
NumberOfInvestments = client.Investments.Count()
LastUpdatedBy = client.Audits.OrderByDescending(m => m.Id).FirstOrDefault(),
}).ToList().Select(data =>
{
return data.client;
}).ToList();
, ( LastUpdatedBy getter/setter, , ).
Select() ( ), Include() EF.