Question

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

Était-ce utile?

La solution

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!

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top