Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mvvm RETRIEVE data in model or viewmodel?

Tags:

mvvm

wpf

c#-4.0

I am learning MVVM. I know model is about my data conceptually. Here is my scenario.

database table definition
create table people (SSN varchar(9),first_name varchar(40),last_name varchar(40))

In my view PeopleV.xaml I defined a DataGrid with 3 columns: SSN, FirstName, LastName.

In my model class PeopleM I exposed 3 properties: SSN, FirstName, LastName.

In my viewmodel class PeopleVM I defined:

PersonInfo = new ObservableCollection<PeopleM>();

Now I need to perform select * from people where SSN >= 'xxxxxxxxx' and put data into a DataTable.

My question is where should I do this (defining the DataTable and fill it with data), in the model PeopleM class or in the viewmodel PeopleVM class?

Thanks.

like image 925
Shawn Avatar asked May 14 '13 18:05

Shawn


1 Answers

Model's are supposed to be dumb data objects that only exist to hold data, so I would not add any kind of data access to that layer.

ViewModels are meant to model the view, and typically would include loading the correct data models for the View to use, however they don't necessarily have to contain the data access code itself.

In most cases, I find it easiest if I put my data access is another layer altogether, and have the ViewModel get the data by interacting with the data access layer.

For example, my ViewModel might have a SearchCommand that when clicked would do something like this:

void Search(string ssn)
{
    PeopleCollection = PeopleRepository.GetPeopleBySsn(ssn);
}

Having a separate layer for data access makes it easier to reuse the data access components, and make the application easier to maintain, update, and test.

like image 67
Rachel Avatar answered Oct 10 '22 22:10

Rachel