[英]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
?是否有可能在 .NET 6 中使用 Entity Framework Core 6 通过设置外键值填充关系导航属性然后调用
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:截图:
after save changes, "department" property still null保存更改后,“部门”属性仍然是 null
When trying this, student.department
remains null after calling SaveChanges
尝试此操作时,调用
SaveChanges
后student.department
仍为 null
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
:如果我这样做,外键
student.departmentId
在调用SaveChanges
后会被填充:
var student = db.Students.Find(9);
student.department = db.Departments.Find(1);
db.SaveChanges();
When trying this student.department remains null after savechanges
尝试此 student.department 时保存更改后仍为 null
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 ). SaveChanges
不会自动加载关系数据,除非上下文已经在跟踪相应的实体( 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:除了使用其中一种选项来加载相关数据(例如@David Browne在其回答中建议的选项)之外,还可以使用以下方法:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.