1

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?

1 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

I am sorry if my point wasn't clear, I am not adding the conversations manually in code. They are bound in the model that is posted back. Conversations are already associated with the client. Now if I were to adopt your code, I did again need to explicitly link conversations to the client.
Well Martin, it worked but I still feel its more explicit. I would have thought these kind of task being performed in the background. Works for now! Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.