我想在我的Repository中添加一个方法,将给定的Generic类型映射到DTO。假设这些是我的Entity
和DTO
:
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的新手。
答案 0 :(得分:1)
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调用一次。