Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVVM where does the code to load the data belong?

Tags:

mvvm

wpf

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

like image 545
cody Avatar asked May 21 '10 04:05

cody


1 Answers

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...

  1. Constructor called by View
  2. GetData method called by ViewModel Ctor
  3. 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...

  1. View/ViewModel (Depends if you are View or ViewModel first) is pulled out of the IoC
  2. IoC Handles the pairing of the View-ViewModel (Convention based)
  3. Data Repository is Injected into the ViewModel
  4. GetData method called by ViewModel Ctor
  5. 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.

like image 154
Agies Avatar answered Sep 30 '22 20:09

Agies