I´m using Entity Framework 5 and Code First.
I have two domain entities Question and Answer for a quiz application. One question has several possible answers. A question also has one correct answer which should reference one of the possible answers. I am experiencing some issues with the combination of a one-to-many and one-to-one relationship between the to entities. See Q1 and Q2.
This is the code for the entities:
public class Question
{
public virtual int Id { get; set; }
[Required]
public virtual string Text { get; set; }
[InverseProperty("Question")]
public virtual ICollection<Answer> PossibleAnswers { get; set; }
public virtual Answer CorrectAnswer { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public virtual DateTime? UpdateStamp { get; set; }
}
public class Answer
{
public virtual int Id { get; set; }
[Required]
public virtual string Text { get; set; }
[ForeignKey("QuestionId")]
public virtual Question Question { get; set; }
public virtual int QuestionId { get; set; }
}
Q1: What should I do to be able to insert the Question object and referenced Answers (thru property PossibleAnswers) in just one roundtrip to the db (eg one call to the contexts SaveChanges)? The error I get when I save the Questions and Answers without adding the Answers first is:
Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values.
To solve that problem I tried the following using fluent API to get the Answers to be added prior to Questions when doing it all with just one call the objectcontexts SaveChanges:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Question>()
.HasOptional(q => q.CorrectAnswer)
.WithRequired();
base.OnModelCreating(modelBuilder);
}
However, that lead me to another error:
Conflicting changes detected. This may happen when trying to insert multiple entities with the same key.
Am I on the right path with the fluent API approach for Q1? Why the error message?
Q2: When deleting a question I realize that there will be an error since the question cannot be deleted before the answers and vice versa. How do I solve this? For instance, is WillCascadeOnDelete supposed to be specified on both Question.CorrectAnswer and Question.PossibleAnswers?