asp.net-mvc – 映射从域实体到DTO的验证属性

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 映射从域实体到DTO的验证属性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个标准的域层实体:
  1. public class Product
  2. {
  3. public int Id { get; set; }
  4.  
  5. public string Name { get; set; }
  6.  
  7. public decimal Price { get; set;}
  8. }

其中应用了某种类型的验证属性

  1. public class Product
  2. {
  3. public int Id { get; set; }
  4.  
  5. [NotEmpty,NotShorterThan10Characters,NotLongerThan100Characters]
  6. public string Name { get; set; }
  7.  
  8. [NotLessThan0]
  9. public decimal Price { get; set;}
  10. }

你可以看到,我已经完全弥补了这些属性。在这里使用的验证框架(NHibernate Validator,DataAnnotations,ValidationApplicationBlock,Castle Validator等)并不重要。

在我的客户层,我也有一个标准的设置,我不使用域实体本身,而是映射到viewmodels(aka DTO),我的视图层使用:

  1. public class Productviewmodel
  2. {
  3. public int Id { get; set; }
  4.  
  5. public string Name { get; set; }
  6.  
  7. public decimal Price { get; set;}
  8. }

让我们说,我希望我的客户端/视图能够执行一些基本的属性级验证。

我看到的唯一方法是,可以重复在viewmodel对象中的验证定义:

  1. public class Productviewmodel
  2. {
  3. public int Id { get; set; }
  4.  
  5. // validation attributes copied from Domain entity
  6. [NotEmpty,NotLongerThan100Characters]
  7. public string Name { get; set; }
  8.  
  9. // validation attributes copied from Domain entity
  10. [NotLessThan0]
  11. public decimal Price { get; set;}
  12. }

这显然不令人满意,因为我现在在viewmodel(DTO)层中重复了业务逻辑(属性级别验证)。

那么可以做什么呢?

假设我使用像AutoMapper这样的自动化工具将我的域实体映射到我的viewmodel DTO,那么将映射属性的验证逻辑转换为viewmodel也不是很酷吗?

问题是:

这是一个好主意吗?

2)如果是这样,可以做吗?如果没有,什么是替代品,如果有?

预先感谢您的任何投入!

解决方法

如果你使用支持DataAnnotations的东西,你应该能够使用元数据类来包含你的验证属性
  1. public class ProductMetadata
  2. {
  3. [NotEmpty,NotLongerThan100Characters]
  4. public string Name { get; set; }
  5.  
  6. [NotLessThan0]
  7. public decimal Price { get; set;}
  8. }

并将其添加到域实体>上的MetadataTypeAttribute中。 DTO:

  1. [MetadataType(typeof(ProductMetadata))]
  2. public class Product

  1. [MetadataType(typeof(ProductMetadata))]
  2. public class Productviewmodel

这不会与所有验证器一起工作 – 您可能需要扩展您选择的验证框架来实现类似的方法

猜你在找的asp.Net相关文章