Linq Includes Alternative

*爱你&永不变心* 提交于 2021-01-28 06:08:48

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!