问题
I am a loading a entity from the database like so
var profileEntity = await Context.Profiles
.Include(x => x.MedicalRecords)
.Include(x => x.DrugHistory)
.Include(x => x.EmploymentStatus)
.SingleOrDefaultAsync(x => x.Id == id);
All is working fine, I was just wondering if there is a better way to include its non generic type properties rather using the Include method
because this particular entity has a lot of properties I need to include
回答1:
It is not possible to automatically eagerly load those properties (Mechanism for statically defining eager loading for navigation properties), but you can create a reusable extension method for this purpose:
public static IQueryable<Profile> IncludeAll(this IQueryable<Profile> query)
{
return query.Include(x => x.MedicalRecords)
.Include(x => x.DrugHistory)
.Include(x => x.EmploymentStatus);
}
Which can be used in a following way:
var profileEntity = Context.Profiles.IncludeAll().SingleOrDefault(x => x.Id == id);
回答2:
One option is to consider turning off lazy loading for those particular navigation properties by making them not virtual. Example below from the MSDN page.
public class Blog
{
public int BlogId { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public string Tags { get; set; }
public ICollection<Post> Posts { get; set; }
}
See the section titled Turning off lazy loading for specific navigation properties at this link for reference.
来源:https://stackoverflow.com/questions/48566437/linq-includes-alternative