I need clarification on how to implement Betty's code solution to transferring data annotation metadata to ViewModels with AutoMapper (see here). Or if you have a better way, please share that. Maybe the implementation of Betty's answer is obvious to someone who knows AutoMapper well, but I'm new to it.
Here is a simple example, what do I add to this code to make Betty's solution work:
// Data model Entity
public class User1
{
[Required]
public int Id { get; set; }
[Required]
[StringLength(60)]
public string FirstName { get; set; }
[Required]
[StringLength(60)]
public string LastName { get; set; }
[Required]
[DataType(DataType.Password)]
[StringLength(40)]
public string Password { get; set; }
}
// ViewModel
public class UserViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Password { get; set; }
}
Current AutoMapper Implementation:
// Called once somewhere
Mapper.CreateMap<User1, UserViewModel>(MemberList.Destination);
// Called in controller method, or wherever
User user = new User() { FirstName = "Tony", LastName = "Baloney", Password = "secret", Id = 10 };
UserViewModel userVM = Mapper.Map<User, UserViewModel>(user);
// NOW WHAT???
I've tried this in global.asax in Application_Start:
var configProvider = Mapper.Configuration as IConfigurationProvider;
ModelMetadataProviders.Current = new MetadataProvider(configProvider);
ModelValidatorProviders.Providers.Clear(); // everything's broke when this is not done
ModelValidatorProviders.Providers.Add(new ValidatorProvider(configProvider));
Also, I had to modify Betty's GetMappedAttributes from:
propertyMap.DestinationProperty.GetCustomAttributes
to:
propertyMap.DestinationProperty.MemberInfo.GetCustomAttributes
(or instead of MemberInfo, is it MemberType?) for this to even build.
But nothing seems to work.