ASP.NET Core with EF Core - DTO Collection mapping
<p>I am trying to use (POST/PUT) a DTO object with a collection of child objects from JavaScript to an ASP.NET Core (Web API) with an EF Core context as my data source. </p>

<p>The main DTO class is something like this (<em>simplified of course</em>):</p>

<pre><code>public class CustomerDto {
    public int Id { get;set }
    ...
    public IList&lt;PersonDto&gt; SomePersons { get; set; }
    ...
}
</code></pre>

<p>What I don't really know is how to map this to the Customer entity class in a way that does not include a lot of code just for finding out which Persons had been added/updated/removed etc.</p>

<p>I have played around a bit with AutoMapper but it does not really seem to play nice with EF Core in this scenario (complex object structure) and collections.</p>

<p>After googling for some advice around this I haven't found any good resources around what a good approach would be. My questions is basically: should I redesign the JS-client to not use "complex" DTOs or is this something that "should" be handled by a mapping layer between my DTOs and Entity model or are there any other good solution that I am not aware of?</p>

<p><em>I have been able to solve it with both AutoMapper and and by manually mapping between the objects but none of the solutions feels right and quickly become pretty complex with much boilerplate code.</em></p>

<h2><strong>EDIT:</strong></h2>

<p>The following article describes what I am referring to regarding AutoMapper and EF Core. Its not complicated code but I just want to know if it's the "best" way to manage this.</p>

<p>(Code from the article is edited to fit the code example above)</p>

<p><a href="http://cpratt.co/using-automapper-mapping-instances/" rel="noreferrer">http://cpratt.co/using-automapper-mapping-instances/</a></p>

<pre><code>var updatedPersons = new List&lt;Person&gt;();
foreach (var personDto in customerDto.SomePersons)
{
    var existingPerson = customer.SomePersons.SingleOrDefault(m =&gt; m.Id == pet.Id);
    // No existing person with this id, so add a new one
    if (existingPerson == null)
    {
        updatedPersons.Add(AutoMapper.Mapper.Map&lt;Person&gt;(personDto));
    }
    // Existing person found, so map to existing instance
    else
    {
        AutoMapper.Mapper.Map(personDto, existingPerson);
        updatedPersons.Add(existingPerson);
    }
}
// Set SomePersons to updated list (any removed items drop out naturally)
customer.SomePersons = updatedPersons;
</code></pre>

<p>Code above written as a generic extension method.    </p>

<pre><code>public static void MapCollection&lt;TSourceType, TTargetType&gt;(this IMapper mapper, Func&lt;ICollection&lt;TSourceType&gt;&gt; getSourceCollection, Func&lt;TSourceType, TTargetType&gt; getFromTargetCollection, Action&lt;List&lt;TTargetType&gt;&gt; setTargetCollection)
    {
        var updatedTargetObjects = new List&lt;TTargetType&gt;();
        foreach (var sourceObject in getSourceCollection())
        {
            TTargetType existingTargetObject = getFromTargetCollection(sourceObject);
            updatedTargetObjects.Add(existingTargetObject == null
                ? mapper.Map&lt;TTargetType&gt;(sourceObject)
                : mapper.Map(sourceObject, existingTargetObject));
        }
        setTargetCollection(updatedTargetObjects);
    }
</code></pre>

<p>.....</p>

<pre><code>        _mapper.MapCollection(
            () =&gt; customerDto.SomePersons,
            dto =&gt; customer.SomePersons.SingleOrDefault(e =&gt; e.Id == dto.Id),
            targetCollection =&gt; customer.SomePersons = targetCollection as IList&lt;Person&gt;);
</code></pre>

<h2><strong>Edit:</strong></h2>

<p>One thing I really want is to delcare the AutoMapper configuration in one place (Profile) not have to use the MapCollection() extension every time I use the mapper (or any other solution that requires complicating the mapping code).</p>

<p>So I created an extension method like this </p>

<pre><code>public static class AutoMapperExtensions
{
    public static ICollection&lt;TTargetType&gt; ResolveCollection&lt;TSourceType, TTargetType&gt;(this IMapper mapper,
        ICollection&lt;TSourceType&gt; sourceCollection,
        ICollection&lt;TTargetType&gt; targetCollection,
        Func&lt;ICollection&lt;TTargetType&gt;, TSourceType, TTargetType&gt; getMappingTargetFromTargetCollectionOrNull)
    {
        var existing = targetCollection.ToList();
        targetCollection.Clear();
        return ResolveCollection(mapper, sourceCollection, s =&gt; getMappingTargetFromTargetCollectionOrNull(existing, s), t =&gt; t);
    }

    private static ICollection&lt;TTargetType&gt; ResolveCollection&lt;TSourceType, TTargetType&gt;(
        IMapper mapper,
        ICollection&lt;TSourceType&gt; sourceCollection,
        Func&lt;TSourceType, TTargetType&gt; getMappingTargetFromTargetCollectionOrNull,
        Func&lt;IList&lt;TTargetType&gt;, ICollection&lt;TTargetType&gt;&gt; updateTargetCollection)
    {
        var updatedTargetObjects = new List&lt;TTargetType&gt;();
        foreach (var sourceObject in sourceCollection ?? Enumerable.Empty&lt;TSourceType&gt;())
        {
            TTargetType existingTargetObject = getMappingTargetFromTargetCollectionOrNull(sourceObject);
            updatedTargetObjects.Add(existingTargetObject == null
                ? mapper.Map&lt;TTargetType&gt;(sourceObject)
                : mapper.Map(sourceObject, existingTargetObject));
        }
        return updateTargetCollection(updatedTargetObjects);
    }
}
</code></pre>

<p>Then when I create the mappings I us it like this:</p>

<pre><code>    CreateMap&lt;CustomerDto, Customer&gt;()
        .ForMember(m =&gt; m.SomePersons, o =&gt;
        {
            o.ResolveUsing((source, target, member, ctx) =&gt;
            {
                return ctx.Mapper.ResolveCollection(
                    source.SomePersons,
                    target.SomePersons,
                    (targetCollection, sourceObject) =&gt; targetCollection.SingleOrDefault(t =&gt; t.Id == sourceObject.Id));
            });
        });
</code></pre>

<p>Which allow me to use it like this when mapping:       </p>

<pre><code>_mapper.Map(customerDto, customer);
</code></pre>

<p>And the resolver takes care of the mapping.</p>