3

I have the following situation: A domain model and a view model(DTO). I perform data validation on both client side and server side on the DTO with data annotation. But also I must perform business rules on the domain model. For this I have chosen the Enterprise Library Validation Application Block. The results of validation are returned as ValidationResults. I have an extension method that copies the errors in ValidationResults, but the thing is that the domain models are not 1:1 mappet to the view model. I use automapper to performe these mappings. So my question is: Is there a way to use the mapping defined in the mapping configuration file to copy the error messages from the key in validation result to the corresponding property in the ModelState

1 Answer 1

3

I figured out this solution:

public static class ModelStateExtensions
{
    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="Tin">ViewModel Type</typeparam>
    /// <typeparam name="Tout">Domain ModelType</typeparam>
    /// <param name="modelstate">controllers modelstate</param>
    /// <param name="results">Results of validation</param>
    public static void AddValidationResult<Tin, Tout>(this ModelStateDictionary modelstate, ValidationResults results)
        where Tout : class
        where Tin : class
    {
        var map = AutoMapper.Mapper.FindTypeMapFor<Tout, Tin>();
        var properties = map.GetPropertyMaps();
        string destinationPropertyName=string.Empty;
        foreach (var result in results)
        {
            var property = properties.FirstOrDefault(pm => pm.SourceMember!=null && pm.SourceMember.Name.Equals(result.Key));
            if (property!=null)
            {
            destinationPropertyName=property.DestinationProperty.Name;
            }
            else
            {
                destinationPropertyName=string.Empty;
            }
             modelstate.AddModelError(destinationPropertyName, result.Message);
           }
   }
}

I added an extension method that based on the AutoMapper mappings I find the property to which the error message must be attached. I hope this will cover all aspects. I welcome any other suggestion!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.