我对实体框架的加载行为有疑问。在我的ASP.NET MVC5应用程序中,有一个ApplicationUser模型,UserProfile模型(用于基本配置文件信息,如名称,地址,性别等),以及UserContactProfile,UserEducationProfile,UserJobProfile模型(用于通常不需要的辅助信息)。
在这种关系中,ApplicationUser拥有UserProfile,而UserProfile拥有UserContactProfile,UserEducationProfile和UserJobProfile。问题是我希望ApplicationUser总是急于加载UserProfile,但是UserProfile要延迟加载子配置文件,例如UserContactProfile。这怎么可能?
我尝试过编写某种代码,但这似乎不起作用:
var user = Db.Users.Find(Id);
下面的一个实际上就是诀窍:
var user = Db.Users.Include(u => u.Profile).Where(u => u.Id == userId).First();
我的想法是我希望自动/懒惰的加载行为是自动的,所以即使是之前没有工作的第一个代码也会提取User和UserProfile信息。这怎么可以实现?我听说编辑ApplicationDbContext的onModelBinding()方法可能有效,但我还没找到方法。