简体   繁体   中英

Entity Framework Core : populating relationship navigation property

Is it possible in .NET 6 with Entity Framework Core 6 to populate the relationship navigation property by setting the foreign key value and then call SaveChanges ?

I tried it but it doesn't seem to work. Although the other way around works perfectly (if I set the navigation property to the related entity).

Screenshots:

setting the foreign key

after save changes, "department" property still null

When trying this, student.department remains null after calling SaveChanges

var student = db.Students.Find(9);
student.departmentId = 1;
db.SaveChanges();

While if I do this, the foreign key student.departmentId gets populated after calling SaveChanges :

var student = db.Students.Find(9);
student.department = db.Departments.Find(1);

db.SaveChanges();

When trying this student.department remains null after savechanges

Setting the foreign key value doesn't load the related department. The use case for setting the foreign key directly is typically to avoid actually loading the related entity.

If you want to load the related entity, you might as well just query it and assign it to the navigation property.

After setting the foreign key property on an entity, you can load the related entity if you want to using explicit loading . eg

db.Entry(student).Reference(b => b.Department).Load();

SaveChanges will not automatically load the relationship data unless context is already tracking the corresponding entity ( Change Tracking in EF Core ). In addition to using one of the options to load the related data (for example the one suggested by @David Browne in his answer), following things will do the trick:

db.Departments.Find(1);
var student = db.Students.Find(9);
student.departmentId = 1;
db.SaveChanges(); // student.department will be filled here

Or even

var student = db.Students.Find(9);
student.departmentId = 1;
db.SaveChanges();
db.Departments.Find(1); // student.department will be filled here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM