5

我需要說明如何使用AutoMapper將數據註釋元數據傳輸到ViewModels的方法(請參閱here)。或者如果你有更好的方法,請分享一下。對於熟悉AutoMapper的人來說,貝蒂答案的實現是很明顯的,但我對此很陌生。如何使用帶有Betty方法的AutoMapper將數據註解元數據傳輸到ViewModel

下面是一個簡單的例子,我該怎麼添加到這個代碼,以使貝蒂的解決方案的工作:

// 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??? 

我在Global.asax中嘗試過這種在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)); 

此外,我不得不修改Betty的GetMappedAttributes從:

propertyMap.DestinationProperty.GetCustomAttributes到: propertyMap.DestinationProperty.MemberInfo.GetCustomAttributes

(或代替的MemberInfo,是它MemberType?)這甚至建立。

但似乎沒有工作。

回答

1

Automapper不使用元數據提供程序,它使用Automapper。

你並不需要直接調用它,它是由MVC自動調用,只要你在Global.asax.cs中與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)); 
+0

謝謝!我將無法立即測試這個,但我希望這可以工作!直到那時,我會將此標記爲答案... –

相關問題