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

后端 未结 5 1334
北恋
北恋 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:28

    Try these things:

    • use the Create() method of DbSet
    • add the new instances to the Answers collection of your Context

    You have set the QuestionId appropriately for EF to realise the relationship. Also, do not explicitly set AnswerId to zero.

    var a = new _uow.Answers.Create();
    a.Text = "AAA";
    a.QuestionId = 14;
    _uow.Answers.Add(a);
    
    var b = new _uow.Answers.Create();
    b.Text = "BBB";
    b.QuestionId = 14;
    _uow.Answers.Add(a);
    

    You may need to make a call to _uow.ChangeTracker.DetectChanges() if you plan on querying the Answers collection of Question 14

提交回复
热议问题