I have read many people say that model types should not be exposed to View, but instead it should be wrapped inside ViewModel types. Is there some example where I can see how is synchronization done between ViewModel and Model data, using Entity Framework. In particular, I need an example of editable collection (example: DataGrid or DataForm displaying Customer list).
So, something like this
http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
but with editable collection data, not just read-only.
An example of what I am interested in:
1) a grid needs to show products. 3 columns are shown:
- Product Code
- Product Name
- Product Type
- Product Unit
Type is an Enum, lets say: ProductType { TypeA, TypeB }. If you find difficult to implement enum, then have it a int, its not a problem. Important thing is that Type cannot be changed if Product was already used as reference in somce other table. I am using this rule, since you can not do this with attributes (Data annotations), and needs to be done on ViewModel side.
Each property on a product class must be bound to CustomerViewModel property. You can put some rules for Code and Name:
Code Unique
Name: Required, MaxLength(30)
EDIT: my main concern is how we do synchronization between ViewModel and EF Model in batch updates. An example would be:
1) when removing Product, if we remove it from ProductViewModel collection and DBContext, what happens when user decides to cancel (made a mistake or anything)? Do we need to reload all Product from database and recreate all ProductViewModels?
2) user changes product and puts product to invalid state (remember that invalid state is still acceptable for object unless we decide to flush it to database). Then user moves cursor to another product, changes it (this product remains in valid state), and execute save command. What should we do at that point?
I have my solutions for all these questions, but I am not sure if they are correct, are there better ways, so the reason why I asked for other opinions from people that are using this method in daily work.
If you need batch update ability then application needs some updates:
1) Do not call SaveChanges from ProductViewModel. Changes should be saved only on pressing “Save” button
2) In the MainViewModel you need to maintain two additional collections: for new items and deleted items. When user presses “Save” button deleted items will be removed from database and new items will be added to database.
3) When user presses “Cancel” button all changes should be reverted. I.e. all fields should be restored to their original state, deleted items should be added back and new items should be deleted
Please see update on github: https://github.com/alexshakurin/EditableDataGridMVVM