我需要澄清如何实现Betty的代码解决方案,以便使用AutoMapper将数据注释元数据传输到ViewModel(请参阅here)。或者,如果你有更好的方法,请分享。也许对于熟悉AutoMapper的人来说,实现Betty的答案是显而易见的,但我是新手。
这是一个简单的例子,我将如何添加到此代码中以使Betty的解决方案有效:
// 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; }
}
当前的AutoMapper实施:
// 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???
我在Application_Start中的global.asax中尝试了这个:
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));
另外,我不得不从:
修改Betty的GetMappedAttributes propertyMap.DestinationProperty.GetCustomAttributes
:
propertyMap.DestinationProperty.MemberInfo.GetCustomAttributes
(或者代替MemberInfo,是会员类型吗?),甚至可以构建它。
但似乎没有任何效果。
答案 0 :(得分:1)
Automapper不使用元数据提供程序,它使用Automapper。
您不需要直接调用它,只要您在Global.asax.cs中启动时使用MVC注册它,它就会被MVC自动调用,例如:
ModelMetadataProviders.Current = new MetadataProvider(
AutoMapper.Mapper.Engine.ConfigurationProvider);
ModelValidatorProviders.Providers.Add(new ValidatorProvider(
AutoMapper.Mapper.Engine.ConfigurationProvider);
或:
ModelMetadataProviders.Current = new MetadataProvider(
(AutoMapper.IConfigurationProvider)AutoMapper.Mapper.Configuration);
ModelValidatorProviders.Providers.Add(new ValidatorProvider(
(AutoMapper.IConfigurationProvider)AutoMapper.Mapper.Configuration));