实体框架可选关系导致“冲突的多重性”

时间:2012-07-19 16:31:00

标签: c# entity-framework ef-code-first

我首先使用Entity Framework代码来处理包含多项选择问题的简单数据库。每个问题都有多个可能的答案,并指定一个作为正确的答案。

public class Question
{
    public int QuestionId { get; set; }

    [ForeignKey("CorrectAnswer")]
    public int CorrectAnswerId { get; set; }
    public string Text { get; set; }

    public virtual ICollection<Answer> Answers { get; set; }

    public virtual Answer CorrectAnswer { get; set; }
}

public class Answer
{
    public int AnswerId { get; set; }
    [ForeignKey("Question")]
    public int QuestionId { get; set; }
    public string Text { get; set; }

    public virtual Question Question { get; set; }
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Answer>()
        .HasRequired(a => a.Question)
        .WithMany(q => q.Answers)
        .HasForeignKey(a => a.QuestionId)
        .WillCascadeOnDelete(false);
}

这一切都很好,但我需要避免因为需要正确答案而无法创建问题的情况,但是因为它需要一个问题而无法创建答案。所以我想让CorrectAnswerId字段为空,允许你创建问题,然后是答案,然后指定正确的答案。

我尝试了以下变体,但总是会遇到“冲突的多重性”异常:

modelBuilder.Entity<Question>()
            .HasOptional(q => q.CorrectAnswer)
            .WithRequired(a => a.Question)
            .Map(p => p.MapKey("CorrectAnswerId"));

1 个答案:

答案 0 :(得分:3)

更改

 int CorrectAnswerId {get;set;}

int? CorrectAnswerId {get;set;}