我正在使用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/zh-CN/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();
假设我们正在谈论EF Core 1.0rc1,则看起来您已经正确创建了模型(除了virtual关键字还没有执行任何操作,因为尚未实现延迟加载)。
由于1.0rc1尚未实现多对多,因此您需要做一些额外的工作。请参阅https://github.com/aspnet/EntityFramework/issues/1368#issuecomment-180066124以获取经典博客Post,Tag和PostTag示例代码。
在您的情况下,您需要向ParticipantSIRAssessmentReport明确添加以下内容:
var participantSIRAssessmentReport = new ParticipantSIRAssessmentReport {ParticipantSIR = participantSIR, ParticipantAssessmentReport = participantAssessmentReport };
_db.ParticipantSIRAssessmentReport.Add(participantSIRAssessmentReport);
_db.SaveChanges();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句