![](/img/trans.png)
[英]EF6: Modifying an entity property with a foreign key relation - Do I need to change the Id or the related object or both?
[英]If I change the Navigation Property for the Parent Entity in a class, do I need to manually change the Foreign Key?
我有一个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; }
}
如果我改变了Parent
属性不同ParentEntity
在数据库中,(更新两个Parents
Collections
的Children
Entities
),我则需要改变ParentId
从一个父实体手动其他?
谢谢!
如果更改实体的导航属性,则将对数据库中的外键列进行相应的更改。
来源: https : //docs.microsoft.com/en-us/ef/core/saving/related-data#changing-relationships
这是观察上述行为的示例代码。
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.