我有这样的模特
public class Question { public string Id { get; set; } = Guid.NewGuid().ToString(); public Answer Answer { get; set; } public List<Variant> Variants { get; set; } public string CorrectVariantId { get; set; } public Variant CorrectVariant { get; set; } } public class Variant { public string Id { get; set; } = Guid.NewGuid().ToString(); public string QuestionId { get; set; } public Question Question { get; set; } } // mapping modelBuilder.Entity<Question>() .HasOne(q => q.CorrectVariant) .WithOne(v => v.Question) .HasForeignKey<Question>(q => q.CorrectVariantId); modelBuilder.Entity<Variant>() .HasOne(v => v.Question) .WithMany(a => a.Variants) .OnDelete(DeleteBehavior.Cascade);
在从EF RC1升级到RTM之前,这种方法非常有效.但现在它抛出:
System.InvalidOperationException:无法在’Question.Variants’和’Variant.Question’之间创建关系,因为’Question.CorrectVariant’和’Variant.Question’之间已经存在关系.导航属性只能参与单个关系.
解决方法
这是RC1中的一个错误/不受欢迎的行为,它已得到修复.
你应该创建另一个属性,比如说另一个关系的SecondQuestion.
public class Question { public string Id { get; set; } = Guid.NewGuid().ToString(); public List<Variant> Variants { get; set; } public string CorrectVariantId { get; set; } public Variant CorrectVariant { get; set; } } public class Variant { public string Id { get; set; } = Guid.NewGuid().ToString(); public string QuestionId { get; set; } public Question Question { get; set; } public Question SecondQuestion { get; set; } }
你的DbContext:
protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Question>() .HasOne(q => q.CorrectVariant) .WithOne(v => v.SecondQuestion) .HasForeignKey<Question>(q => q.CorrectVariantId); modelBuilder.Entity<Variant>() .HasOne(v => v.Question) .WithMany(a => a.Variants).HasForeignKey(x => x.QuestionId).OnDelete(DeleteBehavior.SetNull); base.OnModelCreating(modelBuilder); }
如何使用它:
using (var myDb = new MyDbContext()) { var variantFirst = new Variant(); var variantSecond = new Variant(); var question = new Question(); variantFirst.Question = question; variantSecond.SecondQuestion = question; myDb.Variants.Add(variantFirst); myDb.Variants.Add(variantSecond); myDb.SaveChanges(); }