实体框架:为什么我的相关实体不是“懒惰”的原因?

时间:2012-05-07 07:06:35

标签: asp.net linq entity-framework entity-framework-4 lazy-loading

我有一个Asp.net MVC网站,我在我的数据存储中使用实体框架来访问数据库(使用POCO实体)。

我不是为什么,但有时候,看起来似乎没有完成延迟加载:

代码不工作的示例:

using(BusinessEntities context = new BusinessEntities()){
   User user = context.Users.First(u=>u.Id == parameterId);
   foreach(Post post in user.Posts){//user.Posts is null here and thrown an exception
      //.. doing some things
   }
}

但如果我这样做,那就完美了

using(BusinessEntities context = new BusinessEntities()){
   User user = context.Users.Include("Posts").First(u=>u.Id == parameterId);
   foreach(Post post in user.Posts){//user.Posts is null here and thrown an exception
      //.. doing some things
   }
}

但我不明白为什么延迟加载不起作用:

  • 上下文未被处理
  • 这不是项目匿名对象或类似的东西
  • 我知道我的代码中有很多地方我没有说明这一点。包括并做相关工作
  • 我在我的edmx模型上将Lazy Loading Enabled设置为True

什么可能导致这种行为?

2 个答案:

答案 0 :(得分:1)

Posts属性声明为virtual,以便EF创建的代理实体可以延迟加载该属性。

答案 1 :(得分:0)

请从http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=8363安装EF 4.1以停止在Include中使用魔术字符串。 添加

using System.Data.Entity;

到你的使用陈述。

然后编写以下查询:

using(BusinessEntities context = new BusinessEntities()){
   var user = context.Users.Include(p=>p.Posts).FirstOrDefault(u=>u.Id == parameterId);
   if(user != null)
   {
      foreach(Post post in user.Posts)
      {
         //.. do something
      }
   }
}

有关更多信息,请参阅以下http://blogs.msdn.com/b/adonet/archive/2011/01/31/using-dbcontext-in-ef-feature-ctp5-part-6-loading-related-entities.aspx