Attaching entity with association for modify

218 Views Asked by At

I would modify detached entity with associated collection, ex :

Person and Address are POCO.

When I attach entity and save changes, the collection changes isn't detected, how can I update Person with Address (added and deleted items) ?

Do I to track my collection manually ?

Edit

The synchronization of detached POCO must be manual... EF doesn't purpose merge solution of collection (navigation properties and relations) :(

I compare the current and original collections and I detect the differences

2

There are 2 best solutions below

0
On

If you are using Entity Framework, which I assume you are since you listed it as a tag on your question, then objects only track their changes when they are generated by the entity context.

User someUser = dbEntities.Users.Single(x => x.Username == "test");
someUser.Name = "changed name";
db.SaveChanges();

That code will detect changes and persist them.

User someUser = new User()
{
    Username = "test" //assuming there is already user called test in the database.
}

Creating the user this way will not allow the EF context to detect the changes. Instead you will need to load the entity from the database, update it, and then persist the changes.

string username = "test";
User someUser = db.Users.Single(x => x.Username == username);
TryUpdateModel(someUser, valueProvider); //valueProvider is usually a form collection of some sort, but could be anything that implements IValueProvider.
db.SaveChanges();

This will allow you to pull in an entity, update it, and save the changes.

0
On

You can also work with detached POCO class, and then re-attach it to the context and set the state to modified:

Read this article: http://blogs.msdn.com/b/adonet/archive/2011/01/29/using-dbcontext-in-ef-feature-ctp5-part-4-add-attach-and-entity-states.aspx