1

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?

Sam
  • 15,336
  • 25
  • 85
  • 148

1 Answers1

2

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.

Community
  • 1
  • 1
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • Thanks! While this would work it does not seem to work very well with a generic repository. Or maybe I have not fully grasped the concept yet. – Sam Feb 27 '11 at 22:01
  • @Sam: Example provided in link can be modified for generic repository. But be aware that generic repository is something that everybody want to implement but in the same time it is something which most of the time doesn't work! You always have some entity with special requirements. I'm using generic repository mostly as a base class for specific repositories. – Ladislav Mrnka Feb 28 '11 at 07:00