Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Navigation property returns null after inserting

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;

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

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

like image 923
Libin TK Avatar asked Sep 05 '13 07:09

Libin TK


1 Answers

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

You can use:

db.Students.Include("ClassRoom")

or

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

to eagerly load the nav property

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.

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

Your code should read as follows:

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;
like image 111
Not loved Avatar answered Oct 02 '22 01:10

Not loved