在MVVM设计模式中,模型应该包含其他模型吗? [英] In the MVVM design pattern, should models contain other models?

查看:79
本文介绍了在MVVM设计模式中,模型应该包含其他模型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为我没有看过这样的例子,但是我也没有读过任何明确指出不应这样做的地方.例如,假设我有一些用户模型,其中包含诸如名字,姓氏等常用内容:

public class UserModel
{
    private int userID;
    public int UserID
    {
        get { return userID; }
    }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string MiddleInitial { get; set; }

    ...

}

如果我严格遵循MVVM模式,是否可以使用例如其他模型的列表

public class UserModel
{
    ...
    public List<SomeOtherModel> SomeList { get; set; }

}

或者模型应该仅具有简单类型吗?

解决方案

很简单,是的.

在进行MVVM时,您需要稍微改变一下视角. 模型"的定义与MVC不同,而是包含了所有不是视图和视图模型的内容.这意味着模型"是数据实体(即POCO),它包含任何服务或控制器,还包括业务逻辑,等等:

模型

MVVM中的模型是应用程序域模型的实现,其中包括数据模型以及业务和验证逻辑.模型对象的示例包括存储库,业务对象,数据传输对象(DTO),普通旧CLR对象(PO​​CO)以及生成的实体和代理对象.

引自MSDN文章 MVVM模式

现在您已经改变了看法,如果您的问题变成 POCO(DTO)是否应包含其他POCO?,那么答案仍然是. >

I don't think I have seen an example of this, but I also haven't read anywhere that explicitly states that it shouldn't be done. For example, let's say I have some user model with the usual stuff like first name last name etc:

public class UserModel
{
    private int userID;
    public int UserID
    {
        get { return userID; }
    }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string MiddleInitial { get; set; }

    ...

}

If I were to strictly follow the MVVM pattern, would it be allowed to have, for example, a list of some other model

public class UserModel
{
    ...
    public List<SomeOtherModel> SomeList { get; set; }

}

or should models only have simple types?

解决方案

Quite simply, yes.

When doing MVVM you need to change your perspective a little. The definition of 'model' isn't the same as MVC, instead it encompasses everything that isn't the view and viewmodel. This means the 'model' is a data entity (i.e. POCO), it includes any services or controllers, it includes business logic, etc:

Model

The model in MVVM is an implementation of the application's domain model that includes a data model along with business and validation logic. Examples of model objects include repositories, business objects, data transfer objects (DTOs), Plain Old CLR Objects (POCOs), and generated entity and proxy objects.

Quoted from the MSDN article The MVVM Pattern

So now that you've changed your perspective, if your question becomes Should POCOs (DTOs) contain other POCOs?, then the answer is still yes.

这篇关于在MVVM设计模式中,模型应该包含其他模型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆