c# – EF7(Core)中同一个表的多个关系

前端之家收集整理的这篇文章主要介绍了c# – EF7(Core)中同一个表的多个关系前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有这样的模特
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’之间已经存在关系.导航属性只能参与单个关系.

如果没有从Question模型中删除Variants属性,是否有解决此问题的方法

解决方法

这是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();
}
原文链接:https://www.f2er.com/csharp/239186.html

猜你在找的C#相关文章