2

我首先将实体框架代码用于包含多项选择题的简单数据库。每个问题都有多个可能的答案,并指定一个作为正确答案。

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);
}

这一切都很好,但我需要避免第 22 条问题,即您无法创建问题,因为它需要正确答案,但您无法创建答案,因为它需要问题。所以我想让 CorrectAnswerId 字段可以为空,允许您创建问题,然后是答案,然后指定正确答案。

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

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

1 回答 1

3

改变

 int CorrectAnswerId {get;set;}

int? CorrectAnswerId {get;set;}
于 2012-07-19T16:35:07.703 回答