如何配置EF以自动填充子外键

时间:2016-09-08 14:49:36

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

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

示例模型:

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);

1 个答案:

答案 0 :(得分:1)

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

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它不起作用,很奇怪的行为)