[英]If I change the Navigation Property for the Parent Entity in a class, do I need to manually change the Foreign Key?
I have an Entity
; 我有一个
Entity
;
public class ChildEntity
{
/// <summary>
/// Foreign key for this entity.
/// </summary>
public virtual int ParentId { get; set; }
/// <summary>
/// Navigation Property for this entity.
/// </summary>
public virtual TParentEntity Parent { get; set; }
}
If I am changing the Parent
property to a different ParentEntity
in the Database, (updating both Parents
Collections
of Children
Entities
) do I then need to change the ParentId
from one Parent Entity to the other manually? 如果我改变了
Parent
属性不同ParentEntity
在数据库中,(更新两个Parents
Collections
的Children
Entities
),我则需要改变ParentId
从一个父实体手动其他?
Thanks! 谢谢!
If you change the navigation property of an entity, the corresponding changes will be made to the foreign key column in the database.
如果更改实体的导航属性,则将对数据库中的外键列进行相应的更改。
source: https://docs.microsoft.com/en-us/ef/core/saving/related-data#changing-relationships 来源: https : //docs.microsoft.com/en-us/ef/core/saving/related-data#changing-relationships
Here's a sample code to observe the said behavior. 这是观察上述行为的示例代码。
using (var context = new Context())
{
var child = new ChildEntity();
child.Parent = new TParentEntity();
context.Add(child);
context.SaveChanges();
Console.WriteLine(child.ParentId); // ParentId == 1
child.Parent = new TParentEntity();
Console.WriteLine(child.ParentId); // ParentId == 1
context.SaveChanges();
Console.WriteLine(child.ParentId); // ParentId == 2
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.