How to Transfer DataAnnotation metadata to ViewModel with AutoMapper with Betty's Approach

1.9k views Asked by At

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

There are 1 answers

1
Gianpiero On BEST ANSWER

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));