Mapping Validation Attributes From Domain Entity to DTO

前端 未结 8 2208
轮回少年
轮回少年 2020-12-13 02:21

I have a standard Domain Layer entity:

public class Product
{
    public int Id { get; set; }

    public string Name { get; set; }

    public decimal Price         


        
相关标签:
8条回答
  • 2020-12-13 03:03

    If you use hand-written domain entities, why not put your domain entities in their own assembly and use that same assembly both on the client and server. You can reuse the same validations.

    0 讨论(0)
  • 2020-12-13 03:07

    I've been considering this as well for a while now. I totally understand Brad's reply. However, let's assume I want to use another validation framework that is suitable for annotating both domain entities and view models.

    The only solution I can come up with on paper that still works with attributes would be to create another attribute that "points" to a domain entity's property that you are mirroring in your view model. Here's an example:

    // In UI as a view model.
    public class UserRegistration {
      [ValidationDependency<Person>(x => x.FirstName)]
      public string FirstName { get; set; }
    
      [ValidationDependency<Person>(x => x.LastName)]
      public string LastName { get; set; }
    
      [ValidationDependency<Membership>(x => x.Username)]
      public string Username { get; set; }
    
      [ValidationDependency<Membership>(x => x.Password)]
      public string Password { get; set; }
    }
    

    A framework like xVal could possibly be extended to handle this new attribute and run the validation attributes on the dependency class' property, but with your view model's property value. I just haven't had time to flesh this out more.

    Any thoughts?

    0 讨论(0)
提交回复
热议问题