MVVM, collections and ORM - wpf

I was trying to use MVVM design pattern with WPF and Entity Framework to create a simple application. All goes well and good if the classes are loosely coupled, but if I have sth. like two model classes : Customer and Address and a Customer has a collection of Addresses.
Now for those classes I need to create two VM classes - CustomerVM and AddressVM. CustomerVM should have ObservableCollection of AddressVM objects. Every change made to those VM classes(which includes all CRUD operations on both CustomerVM and AddressVM) needs to be reflected in the model classes - which is why I end up writing a looot of code that eg. subscribes to the changed event of ObservableCollection and if a new object is added then add a new object to the model ... and so on ...
What to do with this? Is this usual while using MVVM? Am I doing everything ok? How to cut down the amount of code needed for such a simple class hierarchy? Are there any frameworks that can create basic VM classes that "behave well" with other classes in hierarchy? What to do if class relationships get MORE complex?
OR TO PUT IT SIMPLE:
How to reflect changes done in vm collections in model collections :
CustomerVM1.AdressesVM.Add(new AddressVM{City="New York"})
should cause an equivalent of:
Customer1.Adresses.Add(new Address{City="New York"})
There's also the same problem the other way round - how to reflect changes done to collections in model to be included in the view model, but I'm more interested in the first one, because it has a more practical application and vm objects can in most cases be simply recreated.

You might be interested in the BookLibrary sample application of the WPF Application Framework (WAF). It shows how to use the Entity Framework and MVVM together.
Short hint: It doesn't create a wrapper ViewModel for every Entity class. Instead, it creates the ViewModel classes for the Views.

You're running into exactly the same problem I ran into when trying to figure out how to keep an ObservableCollection in my ViewModel sync'd with a plain-old-collection in my Model. An ObservableCollection is wonderful because the View can bind to it and automatically change when the collection changes. Unfortunately you've just moved the problem of sync down one level.
One option is to use ObservableCollections everywhere, even in the Model. This isn't very clean architecture because MVVM isn't supposed to make any demands on the Model.
What I did to solve it was to introduce a Presenter, so my architecture looks like this:
View -> ViewModel <-> Presenter <-> Model
Also, I made my ViewModels dumb. Here's how a typical user action takes place from initiation to completion:
User clicks the Add button
ViewModel either raises an event that the Presenter subscribes to, or calls a method on the presenter, or just calls a callback that the Presenter provided to the ViewModel when the ViewModel was constructed. Essentially it delegates the action to the Presenter.
The Presenter calls Add on the Model.
The Model reacts to the Add call, updating all of it's relevant state, including the plain-old-collection.
The presenter, having executed the action on the model, then reads the new state from the Model and writes the state into the ViewModel. Binding takes care of synchronizing the View.
So in your case, the Presenter could subscribe to a CollectionChanged event on the ObservableCollection in the ViewModel, and when it changes, it reacts to the event by calling Add on the Model. On the other hand, when the Presenter is processing some other user action that calls Add on the Model (it knows because it handles all interaction with the Model), then it knows that it has to propagate that change to the ObservableCollection in the ViewModel.
In my code, I simplified the situation... after every user action is executed on the Model by the Presenter, I do a straight copy of all relevant state in the Model to the applicable place in the ViewModel. You're doing a little more work than you need to, but in a typical CRUD type of application, there's no noticeable performance issue. If I have a really big collection of objects, performance could be a problem, and there I drop down to a more fine-grained synchronization (updating only the changed entity), at the expense of more complicated logic.

Related

MVVM, should I put logic in model or view-model (controller)

I am new to MVVM and now doing some MVVM refactorying work on a silverlight project, suppose it is a book shopping application.
The View is a book list, I bind the title of the books to the ViewModel. So I have a public string Title { get; set; } in ViewModel, also a public string Title { get; set; } in Model (am I right?)
Now I want put a event handler to update the book title, should I put the event handler in ViewModel or Model? and what is the Model used for?
In my opinion "Neither"... Add controller classes to the mix of MVVM instead.
The problem with putting controller code in view models is that is makes them harder to test independantly. In many ways I see this as just as bad as code behind.
It seems to me that everyone assumes MVVM has no controllers as they left out the C. MVVM is really a variation of MVC "that just adds ViewModels".
Maybe it should have been called MVCVM instead?
ViewModels are only there to offload the "GUI" code from the view and to contain any data for binding. ViewModels should not do any processing. A good test is that your ViewModel is testable via automated unit tests and has no dependencies on data sources etc. They should have no idea where the data is actually coming from (or who is displaying it).
Although it can be overlooked/avoided, a Controller should be responsible for deciding what data model to display and in which views. The ViewModel is a bridge between Models (the M in MVVM) and Views. This allows simpler "separated" XAML authoring.
The pattern we are using successfully on all recent projects is to register controllers only, in modules, and initialise them at startup. The controllers are very light/slim and the only thing that needs to hang around for the life of the app listening for, or sending, messages. In their initialise methods they then register anything they need to own (views and viewmodels etc). This lightweight logic-only-in-memory pattern makes for slimmer apps too (e.g. better for WP7).
The basic rules we follow are:
Controllers make decisions based on events
Controllers fetch data and place it in appropriate View Model properties
Controllers set ICommand properties of View Models to intercept
events
Controllers make views appear (if not implied elsewhere)
View Models are "dumb". They hold data for binding and nothing else
Views know they display a certain shape of data, but have no idea
where it comes from
The last two points are the ones you should never break or separation of concerns goes out the window.
In simplest terms, the Model is the 'real' underlying data model - containing all the info for the booklist that might be needed by the application, able to get and set data from your database.
The ViewModel is an object that exists primarily to provide data binding for your View. It might be a subset of the Model, or it might combine properties from multiple Models into a single object. It should contain the necessary and sufficient properties to allow the View to do its job.
If the event handler relates to the View, then it belongs in the ViewModel. You might try using the Command Pattern (see Custom WPF command pattern example) if it fits your purpose.

MVVM: does change notification muddy the separation between model and viewmodel?

Let's say I have a model which exposes a collection of objects which I will display and change in a GUI.
So we have Model exposing a collection of ModelItem.
The View binds to a ViewModel which exposes an ObservableCollection of ViewModelItem. ViewModelItem is the Viewmodel of ModelItem
The View contains a ListBox and a DataTemplate. the DataTemplate is for items of type ViewModelItem. The View DataContext points at an instance of ViewModel. The ListBox binds to the ObservableCollection.
I control all the code.
So far so simple. Question:
Is it acceptable to expose the collection on the Model as an ObservableCollection? Further, is it acceptable to implement INotifyPropertyChanged on Model and ModelItem?
My concern is I'm muddying the separation between model and viewmodel, but then common sense says, here's a mechanism for notifying changes to elements in my model, lets use it...
Just wanted to get some perspective from others.
Thanks
Short answer:
YES. Use your notification interfaces on your model when you need to notify of changes. Do not worry about muddying your code with this. Be pragmatic.
Long answer:
My philosophy goes like this: When implementing MVVM, bind directly to model objects when there is nothing extra to do. When you need something new (new behavior, properties the view will utilize, etc) then you wrap the model objects in ViewModel objects. A ViewModel that does nothing but delegate data from the model is nothing but extra code. The moment you need to do something to that data past what the model object gives you, you introduce the layer.
So, to extend my thoughts further on that, (and to answer your question more directly), there needs to be a way for the model to tell the ViewModel when something changes. Often, model data is immutable so it doesn't need this notification mechanism, so it isn't necessary. BUT, it is also often the case that the model DOES change. When that happens, the model has two options: use a custom notification method (events, delegates, etc) or use INotifyPropertyChanged.
If you look at the namespace for INotifyPropertyChanged, it is in System.ComponentModel -- not the view -- so I prefer to use it in the model. It is a well-known interface and you can use it to bind directly to your model from your view. No need to implement anything different.
Taking this philosophy one step further, ObservableCollection is in System.Collections.ObjectModel -- also not view-specific -- and it implements System.Collections.Specialized.INotifyCollectionChanged which also is not view-specific. In other words, ObservableCollection was designed to be a collection that notifies its observers of changes. If you have a model that needs to do that, then ObservableCollection is your tool. It just happens to be convenient (not by accident, though) that WPF and Silverlight use these interfaces for data binding.
I guess this is a long-winded way of saying: "YES. Use your notification interfaces on your model when you need to notify of changes. Do not worry about muddying your code with this. Be pragmatic."
It is definitely acceptable to do both. I would even say it's required to do both. Your common sense abilities work just fine. :)
I would only add that if you don't need all the MVVM functionality for your ModelItems, then you can cut some corners by exposing an ObservableCollection<ModelItem> instead of an ObservableCollection<ViewModelItem>, and modifying your DataTemplate to suit. This will save you quite a bit of "preparation" code, so weigh the pros and cons.
It's certainly acceptable to use change notification in the data model if the data model needs change notification. It's also questionable to use change notification in the data model just because the UI needs change notification.
Generally, I design the data model as if there were no UI, and use the view model as an abstraction layer that hides the data model's implementation details from the UI. On the other hand, in a dynamic application it can be the case that the need for change notification is pervasive enough that it just makes more sense to put it in the data model.
No. It's horrible. Your model should not know how it is used. Giving it this knowledge defeats the object of MVVM.
The model should never know it is being used by WPF, winforms, a dos console, as a service or as a lib. If you tell it this, you are going wrong.
It should also be framework independent, not minding if it's part of MVVM, MVC or MXXX!

MVVM where does the code to load the data belong?

As I wrap my head around the mvvm thing, the view is the view, and the viewmodel is 'a modal of a view' and the model are the entities we are dealing with (or at least that is my understanding). But I'm unclear as to what and when the model entities are populated. So for example:
Lets say I have app that needs to create a new record in a DB. And that record should have default values to start with. Who is responsible for the new record, and getting the default values. Does this have anything to do with MVVM or is that part of a data access layer? Who calls the the viewmodel?
Or for existing records when\where are the records retrieved? And saved if altered?
Thanks
In an overly simplified answer, your ViewModel should contain the LOGIC for controlling what your View displays, as well as how it is allowed to interact with the Model or Data.
Events like Getting data, Saving and Deleting are intercepted through a Command mechanism and pushed into the ViewModel, where they can be tested. Handling 'Dirty' events are also the duty of the ViewModel. As for who Calls the ViewModel, you are entrusting the Calling to the Binding mechanisms available within WPF and Silverlight.
Within the ViewModel it is still about staying with best practices and ensuring that you have a DataAccess layer abstracting your Data Source and possibly using the Repository pattern to abstract that.
The life cycle of a ViewModel could be as simple as the following...
Constructor called by View
GetData method called by ViewModel Ctor
Data received and pushed into existing View databound ObservableCollection property
However since you will probably have a lot of moving parts within the Ctor of the VM, including the Data Repositories Interface you will probably want to work with an IoC. This will make the life cycle of the ViewModel closer to...
View/ViewModel (Depends if you are View or ViewModel first) is pulled out of the IoC
IoC Handles the pairing of the View-ViewModel (Convention based)
Data Repository is Injected into the ViewModel
GetData method called by ViewModel Ctor
Data received and pushed into existing View databound ObservableCollection property
This may seem like more steps, however with an IoC container you are really just calling a single method like IoC.Get(), and the rest of the steps are wired up automatically based on the conventions applied.
I use view-models to control loading (with defaults) and saving my models, and to create collections and objects that I use to bind to my views. This includes setting default values on my models.
State and Bahavior of your view is define in your viewmodel which means all events are declared here.
Who calls the the viewmodel?
it depends who needs it. you can call it in your view.
for existing records when\where are the records retrieved? And saved if altered?
saving and retrieving part is in your viewmodel.
For detailed explanation, visit this site.

How do you keep view logic out of the model and business logic out of the view-model in MVVM?

I can't quite figure out how to get the view model to be notified of changes in the model without adding a bunch of UI specific stuff like INotifyProperyChanged and INotifyCollectionChanged in my model or create tons of different events and do a bunch of things that feel like they're UI specific and should stay out of the model.
Otherwise I'd just have to duplicate all the business logic in the view-model to make sure everything is up to date, and then what's the point of having the model then?
One of the tricky ones that I have in my model is a property of a "Category" class. You can think of it as a tree structure and the property is all leaf-node descendants. Well in the model that property is generated on the fly recursively through all it's children, which is all fine and good. The view-model however needs to bind to that property and needs to know when it changes. Should I just change the model to accommodate the view-model? If I do then the view-model doesn't really do anything at this point, the model raises all the necessary notifications of changes and the view can just bind straight to the model. Also if the model was something I didn't have the source to, how would I get around this?
I disagree that INotifyPropertyChanged and INotifyCollectionChanged are UI-specific. They are in namespaces and assemblies that are not tied to any particular UI stack. For that reason, I typically put that kind of behavior as low in the system as I can (usually the data layer).
If there's some reason you don't want to put it at that level, that's fine. You can put it in at a higher level such as the service or UI layer. However, you need to make sure all changes to the data structures occur through that layer also.

How do I maintain coherency between model and view-model in MVVM pattern?

Problem Statement
I'm writing a very basic WPF application to alter the contents of a configuration file. The data format is an XML file with a schema. I want to use it as a learning project for MVVM, so I have duly divided the code into
Model: C# classes auto-generated from xsd.exe
View-Model: View-friendly representation of the Model.
View: Xaml and empty code behind
I understand how the View-Model can make View-binding a breeze. However, doesn't that leave the View-Model <-> Model semantics very awkward? Xsd.exe generates C# classes with arrays for multiple XML elements. However, at the V-VM level you need Observable Collections.
Questions:
Does this really mean I have to keep two completely different collection types representing the same data in coherence?
What are the best practices for maintaining coherence between the Model and the View-Model?
I'm not a big expert, but I think that is the case yes. The general idea is indeed to propagate change between the view and the viewModel via Binding, and then between the ViewModel and the Model via events (in the Model -> ViewModel direction) or dependency (in the other direction).
I don't know how standard that is, but my understanding of MVVM is that the ViewModel should hold a reference to the model so that when the user modifies the view, the ViewModel should call the appropriate code on the model. The other way round, the Model should raise events when modified, and the ViewModel should update itself accordingly (the ViewModel being an observer to the model).
#Does this really mean I have to keep two completely different collection types representing the same data in coherence?
I think yes. It's pretty boring, but it works quite well. Hopefully, in the future we will have also a code generator to create the ViewModel part.
Karl is working on that: http://karlshifflett.wordpress.com/mvvm/
You need clearly ObservableCollections at the viewmodel so, yes, you will need two
completely different collection types in the model and in the viewmodel.
I have done an article about doing undo / redo in MVVM where you can find a possible solution to this. It uses what I call the MirrorCollection: an ObservableCollection derived class witch automatically obtains his items from a List (the list of the model).
I think it is an interesting solution, you can find the articles here
Part 1: Using the Viewmodel pattern to provide Undo / Redo in WPF
Part 2: Viewmodelling lists (here is the MirrorCollection definition)
Expose Events or delegates in Model and hook to the same in ViewModel, when ever values in the model changes notify to viewmodel via event or delegates and from Viewmodle you can update the UI.
If you want to update it from view model to model as simple as that just call some method pass the new values

Resources