0

I've been told the principal of DRY in Asp.Net MVC is very important. I've also been told that part of adhering to this is not to repeat entity property attributes such as [Required] and [Display(Name="Shuttle Name")] in the ViewModel where possible.

I've also been told that separation between data, business and presentation layers is important. So I’m wondering why an attribute such as [Display] is on an entity in my ProjectName.Entity project. I love the idea of the data layer not having a whiff of the presentation layer’s existence. I would personally prefer to have no display info in my Data layer and no Data entities directly mapped to controls in my Presentation layer.

eg. Use a simple ViewModel which contains the private Shuttle entity property and public properties for any of its properties that require displaying or editing:

private readonly Shuttle shuttle;

public ShuttleViewModel() { this.shuttle = new Shuttle(); }

public ShuttleViewModel(Shuttle shuttle)
{
    this.shuttle = shuttle;
}

[Required]
[Display(Name = "Shuttle Name")]
public string ShuttleName
{
    get { return this.shuttle.Name; }
    set { shuttle.Name = value; } 
}        

I realise that this may be repeating attributes in the ViewModel that are already in the Entity class and mapping data manually but from experience I have found that it Works Every Time. I have also seen some horribly non-intuitive exceptions thrown when a complex entity is uber-mapped to a ViewModel. So I would love some feedback on DRY vs WET.

4

1 回答 1

6

我坚信您不应该将数据实体与视图模型混合使用。

视图模型属性可能因您的数据实体而异,例如某些属性在特定视图模型中是必需的,但对于您的数据实体可能是可选的。

您应该使用 Automapper 之类的工具按约定以编程方式映射您的属性(或为奇数属性使用自定义映射器)

我不同意这会违反 DRY 原则,因为它们都具有不同的功能。

于 2013-10-01T04:42:35.803 回答