Entity Framework 核心多对多未插入

Entity Framework core many to many not inserting

我正在使用 EF7 并且有一个场景需要多对多关系。

我有一个 ParticipantSIR 实体和一个 ParticipantAssessmentReport 实体。他们之间有一个linktableParticipantSIRAssessmentReport

public class ParticipantSIR
{
    public int ParticipantSIRID { get; set; }

    public virtual ICollection<ParticipantSIRAssessmentReport> ParticipantSIRAssessmentReport { get; set; }
    public virtual Participant Participant { get; set; }
}

public class ParticipantAssessmentReport
{
    public int ParticipantAssessmentReportID { get; set; }

    public virtual ICollection<ParticipantSIRAssessmentReport> ParticipantSIRAssessmentReport { get; set; }

}

public partial class ParticipantSIRAssessmentReport
{
    public int ParticipantSIRID { get; set; }
    public int ParticipantAssessmentReportID { get; set; }

    public virtual ParticipantAssessmentReport ParticipantAssessmentReport { get; set; }
    public virtual ParticipantSIR ParticipantSIR { get; set; }
}



modelBuilder.Entity<ParticipantSIRAssessmentReport>(entity =>
        {
            entity.HasKey(e => new { e.ParticipantSIRID, e.ParticipantAssessmentReportID });

            entity.HasOne(d => d.ParticipantAssessmentReport).WithMany(p => p.ParticipantSIRAssessmentReport).HasForeignKey(d => d.ParticipantAssessmentReportID).OnDelete(DeleteBehavior.Restrict);

            entity.HasOne(d => d.ParticipantSIR).WithMany(p => p.ParticipantSIRAssessmentReport).HasForeignKey(d => d.ParticipantSIRID).OnDelete(DeleteBehavior.Restrict);
        });

这似乎是需要使用 EF 核心(包括第三个实体)进行设置的方式。我从中得到了一些信息。 http://ef.readthedocs.io/en/latest/modeling/relationships.html#many-to-many 当我插入数据时,会填充 2 个外部实体,但不会填充 link table.

由于 ParticipantSIR 和 ParticipantAssessmentReport 之间没有导航属性,因此我不确定如何添加 linked 数据。

  _db.ParticipantAssessmentReport.Add(participantAssessmentReport);
            foreach (var sir in participantSirs)
            {
                _db.ParticipantSIR.Add(sir);
            }
            _db.SaveChanges();

要在 EF 中映射多对多关系,您需要将以下内容添加到 DbContextOnModelCreating() 方法中:

modelBuilder.Entity<ParticipantSIR>()
    .HasMany(e => e.ParticipantSIRAssessmentReport)
    .WithMany(e => e.ParticipantSIR)
    .Map(e => e.ToTable("ParticipantSIRAssessmentReport") //Name of the linking table
           .MapLeftKey("ParticipantSIRId") //Name of the Left column
           .MapRightKey("ParticipantSIRAssessmentReportId")); //Name of the right column

从这里开始,将使用每个 类 中的集合来处理关系。

假设我们谈论的是 EF Core 1.0rc1,看起来您已经正确创建了模型(除了 virtual 关键字还没有执行任何操作,因为尚未实现延迟加载)。

由于 1.0rc1 尚未实现多对多,您需要做一些额外的工作。经典博客Post、Tag、PostTag示例代码见https://github.com/aspnet/EntityFramework/issues/1368#issuecomment-180066124

在您的情况下,您需要明确添加到 ParticipantSIRAssessmentReport,如下所示:

    var participantSIRAssessmentReport = new ParticipantSIRAssessmentReport {ParticipantSIR = participantSIR, ParticipantAssessmentReport = participantAssessmentReport };  
    _db.ParticipantSIRAssessmentReport.Add(participantSIRAssessmentReport);  
    _db.SaveChanges();