Find source property name from automapped object

So if you find yourself wanting to find the source property of a view model that caused an entity validation error in the destination when you’re using AutoMapper to map one field to
another then here you go:

First create a TypeMap to perform a lookup against:

var map = Mapper.FindTypeMapFor<YourViewModelClass, YourEntityClass>();

Then for each of the error in the EntityValidationErrors lookup the Destination Property using the Validation Error’s Property name

ex.EntityValidationErrors.SelectMany(e => e.ValidationErrors).ForEach(e =>
{
var errorItem = map.GetPropertyMaps().FirstOrDefault(x => x.DestinationProperty.Name == e.PropertyName);
});

Now the errorItem variable has a property called SourceMember.Name which is the name of the property in the View Model.

So then you can add a error to the ModelState in the loop:

ex.EntityValidationErrors.SelectMany(e => e.ValidationErrors).ForEach(e =>
{
var errorItem = map.GetPropertyMaps().FirstOrDefault(x => x.DestinationProperty.Name == e.PropertyName);
this.ModelState.AddModelError(errorItem.SourceMember.Name, e.ErrorMessage);
});

Then when you return the ViewModel back to the page it will highlight the affected field and display the entity validation error.