ViewModel子对象的命名约定

时间:2013-09-15 21:43:56

标签: asp.net-mvc naming-conventions asp.net-mvc-viewmodel

我正在使用ViewModel方法构建一个ASP.Net MVC应用程序,以使我的域实体与我的UI使用的“模型”分开。我使用以下约定来命名我的ViewModel类。 ViewModelName = ViewName +“ViewModel”。例如:

Index + ViewModel = IndexViewModel

到目前为止,非常好,这是一个相当常见的模式,在StackOverflow和其他地方有很多关于这个主题的指导。我的问题涉及我的ViewModel使用的子对象。如果我的ViewModel需要一个具有与我的域模型对象相同属性的类,我只需在我的ViewModel中包含域模型。例如:

public class PersonViewModel
{
    public int PersonID { get; set; } 
    public Address Address { get; set; }
    public string SomeOtherProperty { get; set; }
}

但是,当我需要一个与我的域模型具有不同属性的子对象时,我不确定使用什么命名约定。例如,如果Address除了Address域模型中的内容之外还需要一些其他属性,我应该怎么称呼它?我认为AddressViewModel是这样的:

public class PersonViewModel
{
    public int PersonID { get; set; } 
    public AddressViewModel Address { get; set; }
    public string SomeOtherProperty { get; set; }
}

但这对我来说感觉不对。我的直觉是,ViewModel后缀应仅适用于顶级ViewModel。

我正在寻找其他开发人员在这种情况下使用的命名约定的建议,特别是在这种情况下你会称之为子对象的什么?

1 个答案:

答案 0 :(得分:1)

我要回答这个问题,因为没有其他人有! (我知道我这次聚会有点晚了!)

多年来,我多次思考过这个问题并尝试过不同的惯例。我接受的一件事是你使用命名约定......

如果您的命名约定是使用' ViewModel'来覆盖您的UI模型类。那么儿童模特应该有相同的后缀,否则你就会违反自己的惯例!

也可以说你有和地址表(或你有什么)和一个客户可以有一个地址,一个公司有一个地址,他们都使用相同的表,然后你们许多人使用相同的子模型为两个父模型。拥有AddressViewModel似乎是正确的,有一天你可能会有一个视图/部分视图模型是IEnumerable<AddressViewModel>

我知道这里没有真正正确的答案,但这是我的答案: - )