繁体   English   中英

如果我在类中更改了父实体的导航属性,是否需要手动更改外键?

[英]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 CollectionsChildren 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.

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