I am using Entity Framework code first for a simple database containing multiple choice questions. Each question has multiple possible answers and specifies one as the correct answer.
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);
}
This all works fine, but I need to avoid the catch 22 situation where you can’t create a question because it needs a correct answer, but you can’t create an answer because it needs a question. So I want to make the CorrectAnswerId field nullable, allowing you to create the question, then the answers, and then specify the correct answer.
I’ve tried variations on the following, but always get a “conflicting multiplicities” exception:
modelBuilder.Entity<Question>()
.HasOptional(q => q.CorrectAnswer)
.WithRequired(a => a.Question)
.Map(p => p.MapKey("CorrectAnswerId"));
Change
to