【问题标题】:If I change the Navigation Property for the Parent Entity in a class, do I need to manually change the Foreign Key?如果更改类中父实体的导航属性,是否需要手动更改外键?
【发布时间】:2018-11-28 17:26:27
【问题描述】:

我有一个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,(同时更新ChildrenChildren EntitiesParents Entities)我是否需要将ParentId 从一个父实体手动到另一个?

谢谢!

【问题讨论】:

    标签: c# database entity-framework code-first


    【解决方案1】:

    如果更改实体的导航属性,数据库中的外键列也会发生相应的更改。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-21
      • 1970-01-01
      相关资源
      最近更新 更多