stephen776
stephen776

Reputation: 9234

Entity Framework 4.1 Modifying Object and Child Collection

If I have Book object which has a child collection of Comments, Can I update the Book and list of Comments together with entity framework?

I have tried :

_context.Books.Attach(book);
_context.ObjectStateManager.ChangeObjectState(book, EntityState.Modified);
_context.SaveChanges();

with no luck...

getting the following error on the first line:

An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key

Upvotes: 2

Views: 1582

Answers (1)

Bobby D
Bobby D

Reputation: 2159

More than likely you have a circular dependency (Books has a foreign key reference to Comments, and Comments back to Books). In this case, the UpdateTranslator within EF is unable to determine the dependency order. As far as I can tell, in this model of development, there is no way to pass a hint to EF to indicate what the order is.

The most common way to solve this (that I have seen) is to do a two-phase commit. Make a change to the Book, save it, then make a change to Comments, and save that. I have found that using the Code First approach allows you to be more specific about the relationships and thereby fix many of the problems that I've had.

Edit:
Here's an example:

using (var context = new BookContext())
{
    book.Title = "This is the new title";
    context.SaveChanges();

    book.Comments.Add(new Comment("This is a comment"));
    context.SaveChanges();
}

If there is a circular dependency, you could not do the above with a single call to SaveChanges.

Upvotes: 2

Related Questions