mvvm在模型或viewmodel中检索数据? [英] mvvm RETRIEVE data in model or viewmodel?
问题描述
我正在学习 MVVM
。我知道模型是关于我的数据概念。这是我的情况。
数据库表定义
create table people(SSN varchar(9),first_name varchar ),last_name varchar(40))
在我的视图中 PeopleV.xaml
我定义了一个包含3列的 DataGrid
: SSN
, FirstName
, LastName
。
在我的模型类
PeopleM 我暴露3个属性: SSN
, FirstName
,姓氏
。
在我的viewmodel类中 PeopleVM
我定义:
PersonInfo = new ObservableCollection< PeopleM>();
现在我需要执行 select * from SSN& xxxxxxxxx'
并将数据放入 DataTable
。
我的问题是在模型 PeopleM
中或在viewmodel <$中定义 DataTable
并填写数据) c $ c> PeopleVM
class?
谢谢。
解决方案模型应该是只存在数据的愚蠢数据对象,所以我不会添加任何类型的数据访问该层。
ViewModels旨在为视图建模,通常包括为要使用的View加载正确的数据模型,但它们不一定必须包含数据访问代码本身。
在大多数情况下,我发现如果我把我的数据访问是另一个层,并让ViewModel通过与数据访问层交互获取数据,最简单。
例如,我的ViewModel可能有一个 SearchCommand
,当点击时会做这样的:
void Search(string ssn)
{
PeopleCollection = PeopleRepository.GetPeopleBySsn(ssn);
}
具有用于数据访问的单独层可以更轻松地重用数据访问组件,并使应用程序更易于维护,更新和测试。
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.
这篇关于mvvm在模型或viewmodel中检索数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!