Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7761091
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T14:03:31+00:00 2026-06-01T14:03:31+00:00

I use AutoMapper to map my domain objects to my view models. I have

  • 0

I use AutoMapper to map my domain objects to my view models. I have metadata in my domain layer, that I would like to carry over to the view layer and into ModelMetadata. (This metadata is not UI logic, but provides necessary information to my views).

Right now, my solution is to use a separate MetadataProvider (independently of ASP.NET MVC), and use conventions to apply the relevant metadata to the ModelMetadata object via an AssociatedMetadataProvider. The problem with this approach is that I have to test for the same conventions when binding the ModelMetadata from the domain as I do with my AutoMapping, and it seems like there should be a way to make this more orthogonal. Can anyone recommend a better way to accomplish this?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-01T14:03:32+00:00Added an answer on June 1, 2026 at 2:03 pm

    I use the approach below to automatically copy data annotations from my entities to my view model. This ensures that things like StringLength and Required values are always the same for entity/viewmodel.

    It works using the Automapper configuration, so works if the properties are named differently on the viewmodel as long as AutoMapper is setup correctly.

    You need to create a custom ModelValidatorProvider and custom ModelMetadataProvider to get this to work. My memory on why is a little foggy, but I believe it’s so both server and client side validation work, as well as any other formatting you do based on the metadata (eg an asterix next to required fields).

    Note: I have simplified my code slightly as I added it below, so there may be a few small issues.

    Metadata Provider

    public class MetadataProvider : DataAnnotationsModelMetadataProvider
    {        
        private IConfigurationProvider _mapper;
    
        public MetadataProvider(IConfigurationProvider mapper)
        {           
            _mapper = mapper;
        }
    
        protected override System.Web.Mvc.ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
        {           
            //Grab attributes from the entity columns and copy them to the view model
            var mappedAttributes = _mapper.GetMappedAttributes(containerType, propertyName, attributes);
    
            return base.CreateMetadata(mappedAttributes, containerType, modelAccessor, modelType, propertyName);
    
    }
    }
    

    Validator Provivder

    public class ValidatorProvider : DataAnnotationsModelValidatorProvider
    {
        private IConfigurationProvider _mapper;
    
        public ValidatorProvider(IConfigurationProvider mapper) 
        {
            _mapper = mapper;
        }
    
        protected override System.Collections.Generic.IEnumerable<ModelValidator> GetValidators(System.Web.Mvc.ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes)
        {   
            var mappedAttributes = _mapper.GetMappedAttributes(metadata.ContainerType, metadata.PropertyName, attributes);
            return base.GetValidators(metadata, context, mappedAttributes);
        }
    }
    

    Helper Method Referenced in above 2 classes

    public static IEnumerable<Attribute> GetMappedAttributes(this IConfigurationProvider mapper, Type sourceType, string propertyName, IEnumerable<Attribute> existingAttributes)
    {
        if (sourceType != null)
        {
            foreach (var typeMap in mapper.GetAllTypeMaps().Where(i => i.SourceType == sourceType))
            {
                foreach (var propertyMap in typeMap.GetPropertyMaps())
                {
                    if (propertyMap.IsIgnored() || propertyMap.SourceMember == null)
                        continue;
    
                    if (propertyMap.SourceMember.Name == propertyName)
                    {
                        foreach (ValidationAttribute attribute in propertyMap.DestinationProperty.GetCustomAttributes(typeof(ValidationAttribute), true))
                        {
                            if (!existingAttributes.Any(i => i.GetType() == attribute.GetType()))
                                yield return attribute;
                        }
                    }
                }
            }
        }
    
        if (existingAttributes != null)
        {
            foreach (var attribute in existingAttributes)
            {
                yield return attribute;
            }
        }
    
    }
    

    Other Notes

    • If you’re using dependency injection, make sure your container isn’t already replacing the built in metadata provider or validator provider. In my case I was using the Ninject.MVC3 package which bound one of them after creating the kernel, I then had to rebind it afterwards so my class was actually used. I was getting exceptions about Required only being allowed to be added once, took most of a day to track it down.
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I would like to use NHibernate Automapper to map the following class: public class
I'm using AutoMapper to map domain entities to view models in an Asp.Net MVC
I have a number of Data Transfer Objects (DTO's) that map onto data structures
I'm trying to use Automapper to map to objects, the issue is one of
I have a domain model that contains a collection and I want to use
Is it possible to use AutoMapper with a single property? I would like to
I know it could be bad to use domain models as view models. If
I am trying to use AutoMapper to map some DTO (data contract) objects received
The service layer of my ASP.NET MVC 3 application uses AutoMapper to map view
I am trying to use automapper to map a list of objects in a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.