【问题标题】:Navigation property returns null after inserting导航属性插入后返回 null
【发布时间】:2013-09-05 07:04:55
【问题描述】:

我已将我的应用程序从 EF4 迁移到 EF5。 我使用下面的代码和以前的版本来获取一个新添加的项目的相关实体。

Student s = new Student();
s.Name = _name;
s.ClassID = _cID;

db.Students.Add(s);
db.SaveChanges();

ClassRoom c = s.ClassRoom;

所以我曾经将特定的类实体获取到c。但现在 s.ClassRoom 返回 null。

如何获取学生的ClassRoom 实体?我必须使用db.ClassRooms.FirstOrDefault(....)吗?

【问题讨论】:

    标签: c# .net entity-framework


    【解决方案1】:

    问题是您尚未加载导航属性。

    你可以使用:

    db.Students.Include("ClassRoom")
    

    using System.Data.Entity;
    db.Students.Include(s=>s.ClassRoom)
    

    急切地加载导航属性

    另一个选项是通过将导航属性标记为虚拟来启用延迟加载。我个人更喜欢前者(渴望加载),因为它鼓励更高性能的代码。

    这里也可以看看我的导航属性文章,我讲的是在起点附近加载http://blog.staticvoid.co.nz/2012/7/17/entity_framework-navigation_property_basics_with_code_first

    您的代码应如下所示:

    Student s = new Student();
    s.Name = _name;
    s.ClassID = _cID;
    
    db.Students.Add(s);
    db.SaveChanges();
    
    //reload the entity from the DB with its associated nav property
    s = db.Students.Include(s=>s.ClassRoom).Single(st=>st.StudentId == s.StudentId);
    ClassRoom c = s.ClassRoom;
    

    【讨论】:

    • 是 EF5 引入的吗?
    • @LibinTK 我认为从 EF 开始就存在。
    • @OndrejJanacek 是的。我以前见过。但即使没有db.Students.Include("ClassRooms"),它也能正常工作
    • @LibinTK with code first 延迟加载在您没有虚拟属性时被禁用。如果您从模型构建器生成上下文,我相信它默认启用。启用延迟加载后,您不会看到此问题。
    • @LukeMcGregor 如何在我的上下文中使用它? var e = db.Students.Include("ClassRoom").FirstOrDefault(p=>p.ClassID==s.ClassID)?
    猜你喜欢
    • 2018-11-07
    • 1970-01-01
    • 2012-11-01
    • 2015-05-30
    • 2015-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多