Navigation property returns null after inserting

前端 未结 1 1938
挽巷
挽巷 2021-01-13 02:27

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 S         


        
相关标签:
1条回答
  • 2021-01-13 03:01

    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;
    
    0 讨论(0)
提交回复
热议问题