'Can AutoMapper.ProjectTo with EF Core update an existing object [duplicate]

I have an existing object that I would like to update with the latest data from my database. I can currently retrieve the EF Core object and then call Mapper.Map to update my dto. Is there a way to use ProjectTo (or something similar) to update my object from the database?

Instead of this:

var result = await context.DbSet
  .FirstOrDefaultAsync(e => e.Id == id, cancellationToken: cancellationToken)
  .ConfigureAwait(false);

return Mapper.Map(result, existingObject);

How can I:

var result = await context.DbSet
  .ProjectTo<TDest>(/* existingObject */)  // I tried .Map, but I got an error that automapper was trying to map this to a child object
  .FirstOrDefaultAsync(e => e.Id == id, cancellationToken: cancellationToken)
  .ConfigureAwait(false);

return existingObject;  // Where existingObject contains the latest database information


Solution 1:[1]

Not sure how it is useful, but you can use the following extension:

public static class MappingExtensions
{
    public static async Task<TDest> ProjectToObjAsync<TDest>(this IQueryable source, IMapper mapper, TDest obj, cancellationToken cancellationToken = default)
    {
        var loadedObj = await source.ProjectTo<TDest>(mapper.Configuration).FirstOrDefaultAsync(cancellationToken);

        if (loadedObj != null)
        {            
            mapper.Map(loadedObj, obj);
        }

        return obj;
    }
}

And usage:

var result = await context.DbSet
    .Where(e => e.Id == id)
    .ProjectToObjAsync(Mapper, existingObject, cancellationToken)
    .ConfigureAwait(false);

return existingObject;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Panagiotis Kanavos