问题
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.
回答1:
The metadata provider isn't used by Automapper, it uses Automapper.
You don't need to call it directly, it's automatically called by MVC as long as you register it with MVC on startup in Global.asax.cs, for example:
ModelMetadataProviders.Current = new MetadataProvider(
AutoMapper.Mapper.Engine.ConfigurationProvider);
ModelValidatorProviders.Providers.Add(new ValidatorProvider(
AutoMapper.Mapper.Engine.ConfigurationProvider);
or:
ModelMetadataProviders.Current = new MetadataProvider(
(AutoMapper.IConfigurationProvider)AutoMapper.Mapper.Configuration);
ModelValidatorProviders.Providers.Add(new ValidatorProvider(
(AutoMapper.IConfigurationProvider)AutoMapper.Mapper.Configuration));
来源:https://stackoverflow.com/questions/21468503/how-to-transfer-dataannotation-metadata-to-viewmodel-with-automapper-with-betty