Sam
Sam

Reputation: 15771

View Model Binding/AutoMapper

I am using Entity Framework 4 with the Service/Repository/EF4/POCO classes technique, and I have a question about View Model binding.

When you map a class to a view model and only take the fields the view needs, then map it back to a new instance of the class to persist to the database, how do you prevent the fields not used in the view from getting overwritten?

Upvotes: 1

Views: 852

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364279

This is usually performed by loading entity from db first and merging incomming data to this entity (ObjectContext will track changes and update only changed properties). Another approach is manually set which properties where modified in state manager:

context.MyEntities.Attach(entity);
context.ObjectStateManager.GetObjectStateEntry(entity).SetModifiedProperty("Name");

Now when you save changes only Name property of the entity will be included in Update SQL command.

When using repostiory check high level example I shown here.

Upvotes: 2

Related Questions