AutoMapper.ProjectTo 可以使用 EF Core 更新现有对象吗

Can AutoMapper.ProjectTo with EF Core update an existing object

我有一个现有对象,我想用我数据库中的最新数据更新它。我目前可以检索 EF Core 对象,然后调用 Mapper.Map 来更新我的 dto。有没有办法使用 ProjectTo(或类似的东西)从数据库更新我的对象?

而不是这个:

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

return Mapper.Map(result, existingObject);

我怎样才能:

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

不确定它有什么用,但您可以使用以下扩展名:

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;
    }
}

和用法:

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

return existingObject;