实体框架核心多对多不插入

时间:2016-04-29 02:33:33

标签: entity-framework entity-framework-core

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

我有一个ParticipantSIR实体和ParticipantAssessmentReport实体。他们之间有一个链接表ParticipantSIRAssessmentReport。

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个外部实体,但不会填充链接表。

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

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

2 个答案:

答案 0 :(得分:1)

假设我们正在谈论EF Core 1.0rc1,看起来你已经正确地创建了你的模型(除了虚拟关键字没有做任何事情,因为懒惰加载还没有实现)。

从1.0rc1开始还没有实现多对多,你需要做一些额外的工作。有关经典博客Post,Tag,PostTag示例代码,请参阅http://guides.rubyonrails.org/layouts_and_rendering.html#using-nested-layouts

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

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

答案 1 :(得分:0)

要在EF中映射多对多关系,您需要在DbContext的{​​{1}}方法中添加以下内容:

OnModelCreating()

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

相关问题