EF Code First forced eager loading

谁说我不能喝 提交于 2019-12-23 07:49:18

问题


I'm using EF 5 with Code First. I have a class that I want to always eager load some properties. I removed the virtual keyword but it's not eager loading:

public class Person
{
   public ICollection<Email> Emails { get; set; } 
   public Profile Profile {get;set;}
}

So by turning off lazy loading, it won't auto eager load right? If so, how do I archive that without using Include()?

Thanks!


回答1:


No, turning off lazy loading by removing the virtual keyword will not automatically enable eager loading. You have to Include the related Entity or Collection like so:

var personWithProfile = ctx.People.Include(x => x.Profile).First();
var personWithProfileAndEmails = ctx.People.
                                           .Include(x => x.Profile)
                                           .Include(x => x.Emails)
                                           .First();

This is a great read from the ADO.NET team blog: http://blogs.msdn.com/b/adonet/archive/2011/01/31/using-dbcontext-in-ef-feature-ctp5-part-6-loading-related-entities.aspx



来源:https://stackoverflow.com/questions/12064905/ef-code-first-forced-eager-loading

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