我有一个标准的领域层实体:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set;}
}
这个表单应用了某些验证属性:
public class Product
{
public int Id { get; set; }
[NotEmpty, NotShorterThan10Characters, NotLongerThan100Characters]
public string Name { get; set; }
[NotLessThan0]
public decimal Price { get; set;}
}
正如您所看到的,我完全虚构了这些属性。在此使用哪个验证框架(如NHibernate Validator、DataAnnotations、ValidationApplicationBlock、Castle Validator等)并不重要。
在我的客户端层中,我还有一个标准设置,我不直接使用领域实体本身,而是将它们映射为视图模型(也称为DTO),供我的视图层使用:
public class ProductViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set;}
}
假设我想让我的客户端/视图执行一些基本的属性级验证。
我唯一能想到的方法是在ViewModel对象中重复验证定义:
public class ProductViewModel
{
public int Id { get; set; }
// validation attributes copied from Domain entity
[NotEmpty, NotShorterThan10Characters, NotLongerThan100Characters]
public string Name { get; set; }
// validation attributes copied from Domain entity
[NotLessThan0]
public decimal Price { get; set;}
}
很明显,这并不令人满意,因为现在我在ViewModel(DTO)层中重复了业务逻辑(属性级别验证)。
那么该怎么办呢?
假设我使用像AutoMapper这样的自动化工具将我的领域实体映射到我的ViewModel DTO,是否也可以将映射属性的验证逻辑以某种方式转移到ViewModel中呢?
问题是:
1)这是一个好主意吗?
2)如果是的话,能否做到?如果不行,还有其他选择吗?
提前感谢您的任何帮助!