views:

27

answers:

1

I have a domain collection type called SavedAnswers and would like to add that collection to my Entity Framework type Entries. I've been trying to figure out what I need to do but I'm getting confused on all the information out there.

Answers has a Identity Primary Key and two Foreign Keys, which brings more issues/questions.

    public void AddEntries(List<SavedAnswers> answers)
    {
        foreach (var item in answers)
        {
            db.Entries.AddObject(Entries.CreateEntries(1, item.QuestionId, item.AnswerId));
        }

        db.SaveChanges();
    }
+2  A: 

Your code looks good except that you should not use the generated factory method on your Entry object. Instead, just create it via the constructor and populate it with object initializer:

public void AddEntries(List answers) {
    foreach (var item in answers) {
        db.Entries.AddObject(new Entry()
        {
            QuestionId = item.QuestionId, 
            AnswerId   = item.AnswerId
        });
    }
    db.SaveChanges();
}

When you use ObjectSet.AddObject method to add newly created objects that do not exist in the store, the entity will get an automatically generated temporary EntityKey and its EntityState will be set to Added.

Morteza Manavi
It works! Thanks for adding in the explanation about the EntityKey and State.
Jisaak