导航属性返回插入空后

导航属性返回插入空后

本文介绍了导航属性返回插入空后,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经迁移从EF4我的应用程序EF5。我用下面的code与previous版本,以获得一个新增加的项目相关的实体。

I've migrated my application from EF4 to EF5.I used the below code with the previous version to get related entity of a newly added item.

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

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

ClassRoom c = s.ClassRoom;

让我用来获取特定的类实体 C 。但现在 s.ClassRoom 返回null。

so I used to get the specific class entity to c. But now s.ClassRoom returns null.

我如何获得学生的教室实体?我一定要使用 db.ClassRooms.FirstOrDefault(....)

How do I get the ClassRoom entity for the student? Do I have to use db.ClassRooms.FirstOrDefault(....)?

推荐答案

问题是,你有没有装导航属性呢。

The issue is that you have not loaded the navigation property yet.

您可以使用:

db.Students.Include("ClassRoom")

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

要急切地加载导航属性。

to eagerly load the nav property

另外一种选择是通过标记与虚拟导航属性启用延迟加载。我个人preFER前(热切加载),因为它鼓励更多的高性能code。

the other option is to enable lazy loading by marking the navigation property with virtual. I personally prefer the former (eager loading) as it encourages more performant code.

另外这里看看我的导航性能的文章中,我谈到加载启动<近href="http://blog.staticvoid.co.nz/2012/7/17/entity_framework-navigation_property_basics_with_$c$c_first" rel="nofollow">http://blog.staticvoid.co.nz/2012/7/17/entity_framework-navigation_property_basics_with_$c$c_first

Also check out my navigation properties article here, I talk about loading near the start http://blog.staticvoid.co.nz/2012/7/17/entity_framework-navigation_property_basics_with_code_first

您code应改为:

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;

这篇关于导航属性返回插入空后,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 15:32