Search code examples
c#asp.net-coreentity-framework-coreautomapper

Use AutoMapper for adding, updating and removing items in List


Does AutoMapper not have a native approach to updating of nested lists where the instances need to be removed, added or updated?

I am using AutoMapper in my ASP.Net Core application with EF Core to map my API resources to my models. This has been working fine for most of my application, but I am not pleased with my solution for updating mapped nested lists where the listed instances need to persist. I don't want to overwrite the existing list, I want to delete instances that are no longer in my incoming resource, add new instances, and update existing instances.

What I am currently doing is a custom mapping, but I feel this is such a generic case that I expect AutoMapper to be able to handle this by some extension.


Solution

  • Thanks to Ivan Stoev I started looking at AutoMapper.Collection, which is really the extension I had hoped to find. After implementing my lists get updated as I had wanted to. The configuration is straightforward in my usage as I only have to specify the Id of my objects.

    My startup configuration is changed to:

    using AutoMapper;
    using AutoMapper.EquivalencyExpression;
    [....]
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddAutoMapper(cfg => {
                    cfg.AddCollectionMappers();
                    });
            }
    [....]
    

    And my mapping profile:

        CreateMap<SubItemDTO, SubItem>()
            .EqualityComparison((x, y) => x.Id == y.Id);