Mapping Validation Attributes From Domain Entity to DTO

If you’re using something supporting DataAnnotations, you should be able to use a metadata class to contain your validation attributes:

public class ProductMetadata 
{
    [NotEmpty, NotShorterThan10Characters, NotLongerThan100Characters]
    public string Name { get; set; }

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

and add it in the MetadataTypeAttribute on both the domain entity & DTO:

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

and

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

This won’t work out of the box with all validators – you may need to extend your validation framework of choice to implement a similar approach.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)