xrnd
xrnd

Reputation: 1342

Entity Framework Nested Entities Add or Update

I have two tables. Client and Conversations. In the view for creating/editing clients, there is also an option for adding Conversations associated to the client (using BeginCollectionItem). When I try to update (in the edit view) using the following code:

db.Clients.Attach(client);
db.Entry(client).State = EntityState.Modified; //Conversations not added

The fields in the Client table are updated but the conversations are not added. I do not face this issue while creating a client.

db.Clients.Add(client); //Conversations are added

Is it possible to accomplish this without having to add the conversations explicitly?

Upvotes: 1

Views: 3483

Answers (1)

Martin Booth
Martin Booth

Reputation: 8595

First attach the client, then add the conversation to it:

var client = db.Clients.Attach(new Client());
client.Conversations.Add(conversation);

db.SaveChanges();

No need to change the client's state programatically.. if you attach the client to the context first, entity framework will track the changes.

Edit:

Since the object is already constructed when you attach it to the context, you need to tell EF that the conversation children have either been Added or Modified

foreach (var conversation in client.Conversations)
{
    if (conversation.Id == default(int))        
        context.Entry(conversation).State = EntityState.Added;
    else
        context.Entry(conversation).State = EntityState.Modified;
}

Upvotes: 2

Related Questions