AutoMapper / AutoMapper.Collection

AutoMapper support for updating existing collections by equivalency
MIT License
245 stars 59 forks source link

How to use Collections with Profile configuration? #157

Closed achobanov closed 3 years ago

achobanov commented 3 years ago

I've configured my AutoMapper with MappingProfiles inheriting from AutoMapper.Profile. How can I configure it to use Automapper.Collection without access to the IMapperConfigurationExpression interface?

TylerCarlson1 commented 3 years ago

You can't. It needs the IMapperConfigurationExpression to inject the feature that will allow for collection mapping before any configuration starts. This needs to be done at the top most level, and shouldn't be done on the profile level. You should add collection mappers then add custom profiles.

vijayathii commented 1 year ago

@achobanov Could you please share the code sample as suggested by @TylerCarlson1. I am not clear with the comment "It needs to be done at the top most level"

achobanov commented 1 year ago

@vijayathii Unfortunately I can't, I've since moved away from AutoMapper.Collections.

However his answer simply means that you can only configure it using IMapperConfigurationExpression. Another way of saying it is that when you reach the Profile configuration stage some stuff has already been configured by the library and you can no longer access those configurations needed for Collections to work.

If you need a sample of how to register AutoMapper.Collections then one such can be found conveniently in their Readme.

Tasteful commented 1 year ago

If you run the cfg.AddCollectionMappers() in the root configuration, then you should be able to map the different equivalency expression inside profiles.

        public class TestProfile : Profile
        {
            public TestProfile()
            {
                CreateMap<ThingDto, Thing>()
                    .EqualityComparison((dto, entity) => dto.ID == entity.ID);
            }
        }
vijayathii commented 1 year ago

Thanks @Tasteful. We need to add at the time of configuring the services.

builder.Services.AddAutoMapper(cfg => { cfg.AddCollectionMappers(); }, typeof(Program));