0

Synopsis

I'm creating a POC to migrate an old web forms app up to MVC. As part of this, I want it to use new (to this place) tools such as Automapper, jQuery, Entity Framework, etc, etc.

I've gotten stuck on how to properly set up and use Automapper profiles. I think I might be getting confused by seeing help which goes with older Automapper versions.

I imagine I'm overlooking something really simple.

Details

I have a factory method to get some things from a database and use automapper to convert them from the EF representation to a db-agnostic representation. At first, I just plugged the mapping right in my query method:

            var typeConfig = new MapperConfiguration(cfg => cfg.CreateMap<Db.ClaimType, ApplicationObjects.Claims.ClaimType>()
                .ForMember(dest => dest.Id, opts => opts.MapFrom(src => src.ID)));

            var aoTypes = typeConfig.CreateMapper().Map<List<Db.ClaimType>, List<ApplicationObjects.Claims.ClaimType>>(claimTypes);

            return aoTypes;

That works fine.

Now, I want us to be able to declare each mapping once in the application, so any update gets applied to all uses. I read about Automapper profiles, and created a simple profile:

    public class ClaimProfile : Profile
    {
        public ClaimProfile()
        {
            var claimTypeMappingDbToAO = CreateMap<Db.ClaimType, ApplicationObjects.Claims.ClaimType>()
                .ForMember(dest => dest.Id, opts => opts.MapFrom(src => src.ID));
            var claimMappingDbToAO = CreateMap<Db.Claim, ApplicationObjects.Claims.Claim>()
                                                .ForMember(dest => dest.Id, opts => opts.MapFrom(src => src.ClaimID))
                                                .ForMember(dest => dest.ClaimTypeId, opts => opts.MapFrom(src => src.ClaimType))
                                                .ForMember(dest => dest.ClaimType, opts => opts.MapFrom(src => src.ClaimType1));
        }
    }

and a config class, which is executed in Global.asax's Application_Start

    public class AutoMapperConfig
    {
        public static void Initialize()
        {
            MapperConfiguration config = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile(new ClaimProfile());
            });

        }
    }

It's not clear to me how I should change my factory to use the profile version of the mapping.

  • 1
    http://docs.automapper.org/en/latest/Dependency-injection.html – Lucian Bargaoanu Nov 26 '19 at 16:45
  • @Lucian Thank you, I'd seen that but didn't fully understand. I've gotten off my POC and back to real-world problems for now. When I get back to POC, I'll study this again and see if I can grok it better. – Scott Peterson Dec 04 '19 at 15:42

0 Answers0