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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With