如何使用EF Core Code-First在自身上桥接表

时间:2019-04-11 03:17:06

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

这是我过去使用数据库优先方法多次执行的操作。我现在正在使用EF Core进行代码优先的尝试,但是我却以失败告终。

我有以下模型:

public class DataMapping
{
    [Key]
    [Column(Order = 1)]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }

    public string Model { get; set; } 
    public string Property { get; set; }
    public bool IgnoreProperty { get; set; } 

    [NotMapped] //<-- I had to add this as the migration was complaining that it did not know what the relation was
    public List<DataMappingRelation> DataMappingRelations { get; set; }

    public DateTime DateCreated { get; set; } = DateTime.UtcNow;
    public DateTime? DateModified { get; set; }
}

和一个Bridge模型,该模型基本上在同一表中的两个DataMapping项之间创建关系:

public class DataMappingRelation
{
    [Key]
    [Column(Order = 1)]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }

    [ForeignKey("DataMappingId")]
    public long? DataMapping1Id { get; set; }
    public DataMapping DataMapping1 { get; set; } 

    [ForeignKey("DataMappingId")]
    public long? DataMapping2Id { get; set; }
    public DataMapping DataMapping2 { get; set; }
}

但是此呼叫不起作用:

return _context.DataMappings.Where(x => x.Model == type.FullName)
            .Include(x=>x.DataMappingRelations)
            .ToList();

它不喜欢Include并抛出null ref异常。

我基本上要做的就是针对给定的“ DataMapping”,根据“ DataMappingRelations”表中的关系获取所有相关的DataMapping项。

是的,我看过this answer,但这又是两个单独表的示例,而不是一个单独的表在自身上桥接。

我怀疑我做错了所有这一切。我该如何工作?我发现的所有示例都桥接两个单独的表。这将桥接同一张表。

1 个答案:

答案 0 :(得分:1)

它与many-to-many一起使用,但您的整个配置看起来很混乱。

因此,首先,您的DataMapping模型类应包含DataMappingRelation中两个外键的两个列表导航属性,如下所示:

public class DataMapping
{
    ......

    public List<DataMappingRelation> DataMapping1Relations { get; set; }

    public List<DataMappingRelation> DataMapping2Relations { get; set; }

    .........
}

现在从[ForeignKey("DataMappingId")]DataMapping1外键中删除DataMapping2属性,如下所示:

public class DataMappingRelation
{
    [Key]
    [Column(Order = 1)]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }

    public long? DataMapping1Id { get; set; }
    public DataMapping DataMapping1 { get; set; } 

    public long? DataMapping2Id { get; set; }
    public DataMapping DataMapping2 { get; set; }
}

然后Fluent API的配置应如下所示:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
     base.OnModelCreating(modelBuilder);

     modelBuilder.Entity<DataMappingRelation>()
         .HasOne(dmr => dmr.DataMapping1)
         .WithMany(dm => dm.DataMapping1Relations)
         .HasForeignKey(dmr => dmr.DataMapping1Id)
         .OnDelete(DeleteBehavior.Restrict);

     modelBuilder.Entity<DataMappingRelation>()
         .HasOne(dmr => dmr.DataMapping2)
         .WithMany(dm => dm.DataMapping2Relations)
         .HasForeignKey(dmr => dmr.DataMapping2Id)
         .OnDelete(DeleteBehavior.Restrict);
}