如何在 GenericRepository 中使用 Automapper 将实体映射到 DTO?

How to use Automapper inside GenericRepository to Map Entities to DTO?

我想向我的存储库添加一个方法,将给定的通用类型映射到 DTO。假设这些是我的 EntityDTO:

public class User : BaseEntity
{
    public string firstName { get; set; }
    public string lastName { get; set; }

    List<UserOperation> operations { get; set; }
}

public class Operation : BaseEntity
{
    public string src { get; set; }
    public string title { get; set; }
}

public class UserOperation : BaseEntity
{
    public int sortOrder { get; set; }

    public Int64 userId { get; set; }
    [JsonIgnore]
    public virtual User user { get; set; }

    public Int64 operationId { get; set; }
    [JsonIgnore]
    public virtual Operation operation { get; set; }
}

我想在GenericRepository中使用这样的方法:

public interface IGenericRepository<T, Key>
{
PagedResult<U> getAllGrid<U>(IQueryable<T> query, SearchOption option) where U : class;
}

public class GenericRepository<T, Key> : IGenericRepository<T, Key> where T : BaseEntity
{
    public PagedResult<U> getAllGrid<U>(IQueryable<T> query, SearchOption option) where U : class
            {
                    Mapper.CreateMap<T, U>();

                    var totalRecordsCount = query.Count();

                    if (totalRecordsCount != 0)
                    {
                        List<U> mappedEntities = new List<U>();
                        foreach (T item in query.OrderBy(option.orderBy + " " + option.orderByType).Skip(option.start * option.size).Take(option.size))
                        {
                            mappedEntities.Add(Mapper.Map<T, U>(item));
                        }

                        return new PagedResult<U>()
                        {
                            Result = true,
                            Records = JsonConvert.SerializeObject(mappedEntities)
                        };
                    }
                    else
                        return new PagedResult<U>() { Result = true, MainRecords = null };
            }
}

public class UserOperationRepository : GenericRepository<UserOperation, Int64>, IUserOperationRepository
{
    public UserOperationRepository()
    {
        base.context = new AppContext();
    }
    public PagedResult<UserOperationDTO> getAllGrid(long userId, SearchOption option)
    {
        var query = base.context.Set<UserOperation>().AsQueryable();

        return base.getAllGrid<UserOperationDTO>(query, option);
     }
 }

我是 automapper 和 GenericRepository 的新手。

AutoMapper 支持投影 - 你不需要调用 Mapper.Map:

var mappedEntities = query
    .OrderBy(option.orderBy + " " + option.orderByType)
    .Skip(option.start * option.size)
    .Take(option.size)
    .Project().To<U>()
    .ToList();

我还会将您所有的 CreateMap 集中在一个地方 - CreateMap 很昂贵,并且只打算在每个 AppDomain 中调用一次。