How can I use EF to add multiple child entities to an object when the child has an identity key?

后端 未结 5 1332
北恋
北恋 2021-01-02 02:23

We are using EF5 and SQL Server 2012 the following two classes:

public class Question
{
    public Question()
    {
        this.Answers = new List

        
5条回答
  •  囚心锁ツ
    2021-01-02 02:36

    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();
    
    // ...
    

提交回复
热议问题