加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-15 19:15:08 所属栏目:asp.Net 来源:网络整理
导读:我有一个标准的域层实体: 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,NotSh
我有一个标准的域层实体:
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等)并不重要。

在我的客户层,我也有一个标准的设置,我不使用域实体本身,而是映射到ViewModels(aka 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,NotLongerThan100Characters]
    public string Name { get; set; }

    // validation attributes copied from Domain entity
    [NotLessThan0]
    public decimal Price { get; set;}
}

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

那么可以做什么呢?

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

问题是:

这是一个好主意吗?

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

预先感谢您的任何投入!

解决方法

如果你使用支持DataAnnotations的东西,你应该能够使用元数据类来包含你的验证属性:
public class ProductMetadata 
{
    [NotEmpty,NotLongerThan100Characters]
    public string Name { get; set; }

    [NotLessThan0]
    public decimal Price { get; set;}
}

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

[MetadataType(typeof(ProductMetadata))]
public class Product

[MetadataType(typeof(ProductMetadata))]
public class ProductViewModel

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读