Mapping Validation Attributes From Domain Entity to DTO

Martin Suchanek picture Martin Suchanek · Jan 15, 2010 · Viewed 8.9k times · Source

I have a standard Domain Layer entity:

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

    public string Name { get; set; }

    public decimal Price { get; set;}
}

which has some kind of validation attributes applied:

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

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

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

As you can see, I have made up these attributes completely. Which validation framework (NHibernate Validator, DataAnnotations, ValidationApplicationBlock, Castle Validator, etc) in use here is not important.

In my client layer, I also have a standard setup where I don't use the Domain entities themselves, but instead map them to ViewModels (aka DTO) which my view layer uses:

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

    public string Name { get; set; }

    public decimal Price { get; set;}
}

Let's then say that I want my client/view to be able to perform some basic property-level validations.

The only way I see I can do this is to repeat the validation definitions in the ViewModel object:

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;}
}

This is clearly not satisfactory, as I have now repeated business logic (property-level validation) in the ViewModel (DTO) layer.

So what can be done?

Assuming that I use an automation tool like AutoMapper to map my Domain entities to my ViewModel DTOs, wouldn't it also be cool to somehow transfer the validation logic for the mapped properties to the ViewModel as well?

The questions are:

1) Is this a good idea?

2) If so, can it be done? If not, what are the alternatives, if any?

Thank you in advance for any input!

Answer

Sam picture Sam · Feb 11, 2010

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.