EF Core 2.0中的一对多关系

时间:2019-06-07 16:34:22

标签: entity-framework-core

伙计,我有以下表格结构

public class PolicySubStatus
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int PolicySubStatusId { get; set; }
    public string SubStatusName { get; set; }
    public IList<PolicySubStatusReason> PolicySubStatusReason { get; set; }        

}
public class PolicySubStatusReason
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int PolicySubStatusReasonId { get; set; }
    public string SubStatusReason { get; set; }
}

这将创建迁移,并使用适当的FK对一对多关系正确地更新数据库。

我的问题是使用ModelBuilder播种数据,如何在数据中创建联接? 我有这个

modelBuilder.Entity<PolicySubStatusReason>().HasData(
            new PolicySubStatusReason
            {
                PolicySubStatusReasonId = 1,                      
                SubStatusReason = "Claim Repair Documents"

            },
         new PolicySubStatusReason
            {
                PolicySubStatusReasonId = 2,
                SubStatusReason = "Cause of Loss Statement"

            },

我该如何播种PolicySubStatus以引用上述PolicySubStatusReason列表?

1 个答案:

答案 0 :(得分:1)

由于您没有公开FK属性PolicySubStatusReason,因此可以使用匿名类型来表示种子的PolicySubStatusReason.PolicySubStatusId

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<PolicySubStatus>().HasData(
        new PolicySubStatus
        {
            PolicySubStatusId = 999,
            SubStatusName = "abc"
        });

    modelBuilder.Entity<PolicySubStatusReason>().HasData(
        // anonymous type
        new
        {
            PolicySubStatusReasonId = 1,
            PolicySubStatusId = 999,
            SubStatusReason = "Claim Repair Documents"
        },
        new
        {
            PolicySubStatusReasonId = 2,
            PolicySubStatusId = 999,
            SubStatusReason = "Cause of Loss Statement"
        });
}