c# - 导航属性在插入后返回 null

标签 c# .net entity-framework

我已将我的应用程序从 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(....) 吗?

最佳答案

问题是您还没有加载导航属性。

您可以使用:

db.Students.Include("ClassRoom")

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

急切加载 nav 属性

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

另请查看我的导航属性文章,我谈到在开始附近加载 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;

关于c# - 导航属性在插入后返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18629843/

相关文章:

c# - 使用两个条件在 Entity Framework 中指定项目列表内容

c# - C# 中的图像处理库

c# - 将字符串转换为小数点后两位

.net - 将 DataGridViewColumn 绑定(bind)到第二级对象

c# - 如何使用代码优先 Entity Framework 指定外键

c# - 如何仅比较 EF 中 DateTime 的日期组件?

c# - TreeView 验证

c# - 如何使用 log4net 在日志文件中添加一个空行?

c# - 将 DBNull.Value 和空文本框值传递给数据库

c# - 如何从 .Net 打印对话框中删除打印机?