如何使用EF Core Code-First桥接自己的表

问题描述 投票:1回答:1

这是我过去使用数据库优先方法多次执行的操作。我现在正在尝试使用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并抛出空引用异常。

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

是的,我已经看过this answer,但是再次,它是两个单独的表的一个例子,而不是一个单独的表桥接自己。

我怀疑我做错了所有这些。我怎样才能使这个工作?我发现的所有例子都是连接两个单独的表格。这将是桥接同一张桌子。

c# ef-code-first entity-framework-core
1个回答
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);
}
© www.soinside.com 2019 - 2024. All rights reserved.