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

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 从一个父实体更改为另一个父实体吗?

谢谢!

If you change the navigation property of an entity, the corresponding changes will be made to the foreign key column in the database.

来源: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
}