Attaching an association object to change

I would modify a single object with an associated collection, for example:

Person and address are POCO.

When I attach an entity and save changes, the collection changes are not detected, how can I update Person with Address (added and deleted elements)?

Do I need to manually track my collection?

Edit

The synchronization of an individual POCO must be manual ... EF is not intended to combine the solution of a collection (properties and navigation relationships): (

I compare current and original collections and discover differences

+4
source share
2 answers

If you are using the Entity Framework, and I assume that you have since you indicated it as a tag in your question, then objects only track their changes when they are created by the entity context.

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

This code will detect the changes and save them.

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

Creating a user this way will not allow the EF context to detect changes. Instead, you will need to load the object from the database, update it, and then save 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 out the entity, update it, and save the changes.

+1
source

You can also work with the disabled POCO class and then reattach it to the context and set the changed state:

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

+1
source

Source: https://habr.com/ru/post/1342671/


All Articles