mvvm RETRIEVE data in model or viewmodel?

后端 未结 1 1968
不知归路
不知归路 2021-01-18 10:58

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

database table definition
create table people (SSN varchar(         


        
1条回答
  •  北海茫月
    2021-01-18 11:13

    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.

    0 讨论(0)
提交回复
热议问题