We are using EF5 and SQL Server 2012 the following two classes:
public class Question
{
public Question()
{
this.Answers = new List
Did you mentioned that you are adding a
two times...?!
question.Answers.Add(a);
question.Answers.Add(a);
Usually, to add items which their id is identity, you must skip setting the id. You also should add the [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
attribute to these IDs:
public class Answer
{
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int AnswerId { get; set; }
public string Text { get; set; }
public int QuestionId { get; set; }
public virtual Question Question { get; set; }
}
And add data like this:
var a = new Answer{
Text = "AAA",
QuestionId = 14
};
var b = new Answer
{
Text = "BBB",
QuestionId = 14
};
dbContext.Answers.Add(a);
dbContext.Answers.Add(b);
dbContext.SaveChanges();
// ...