【问题标题】:How to configure EF to automatically populate child Foreign Key如何配置 EF 以自动填充子外键
【发布时间】:2016-09-08 14:49:36
【问题描述】:

当父类不使用数据库生成的标识符时,如何配置实体框架以自动填充子对象中的外键。

示例模型:

public class Parent
{
    [Key]
    public string Name { get; set; }

    public virtual List<Child> Children { get; set; }
}

public class Child
{
    [Key]
    [Column(Order = 1)]
    public string ParentName { get; set; }

    [Key]
    [Column(Order = 2)]
    public string ChildName { get; set; }
}

示例种子方法:

context.Parents.AddOrUpdate(p => p.Name,
    new Parent
    {
        Name = "Test",
        Children = new List<Child>
        {
            new Child {ParentName = "Test", ChildName = "TestChild"},
            new Child {ParentName = "Test", ChildName = "NewChild"}
        }
    });

是否可以配置 EF,以便我不必为子列表中的每个新子手动设置 ParentName = "Test"?

编辑 - 这是生成的迁移

CreateTable(
    "dbo.Parents",
    c => new
    {
        Name = c.String(nullable: false, maxLength: 128),
    })
    .PrimaryKey(t => t.Name);

CreateTable(
    "dbo.Children",
    c => new
    {
        ParentName = c.String(nullable: false, maxLength: 128),
        ChildName = c.String(nullable: false, maxLength: 128),
    })
    .PrimaryKey(t => new {t.ParentName, t.ChildName})
    .ForeignKey("dbo.Parents", t => t.ParentName, cascadeDelete: true)
    .Index(t => t.ParentName);

【问题讨论】:

  • 为什么不能将关系配置为FK?
  • @Sampath 按照惯例配置了 FK。我添加了迁移以显示它正在配置。我只是想知道当我将项目添加到父子列表时,EF 是否可以自动填充 FK ParentName。

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


【解决方案1】:

您可以向子类添加导航属性,配置模型,然后一切正常

public class Child
{
    [Key]
    [Column(Order = 1)]
    public string ParentName { get; set; }

    [Key]
    [Column(Order = 2)]
    public string ChildName { get; set; }

    public virtual Parent Parent { get; set; } // <-- Add this
}

这是配置

        modelBuilder.Entity<Parent>()
            .HasMany(_ => _.Children)
            .WithRequired(_ => _.Parent)
            .HasForeignKey(_ => _.ParentName);

(没有 Child.Parent 它不起作用,非常奇怪的行为)

【讨论】:

  • 谢谢@bubi 我只需要添加虚拟导航属性。不需要该配置。就我而言,我不需要导航属性,所以我没有它。 EF 在覆盖并设置 Child.Parent 导航属性时必须填充 ParentName 属性。
  • 我总是添加配置。我害怕 EF 更新 :)
猜你喜欢
  • 2012-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多