你好,我已经写了一个通用方法将DTO映射到POCO,反之亦然。但是,当我传递POCO列表时,它不会将其映射到DTO列表。看下面:
public static class BaseMapper<T, TD>
where T : class
where TD : class
{
public static List<TD> Map(List<T> entity)
{
var config = new MapperConfiguration(cfg => cfg.CreateMap<List<T>, List<TD>>());
var mapper = config.CreateMapper();
return mapper.Map<List<TD>>(entity);
}
public static List<T> Map(List<TD> dto)
{
var config = new MapperConfiguration(cfg => cfg.CreateMap<List<TD>, List<T>>());
var mapper = config.CreateMapper();
return mapper.Map<List<T>>(dto);
}
}
这是我的POCO:
public partial class Company : Core
{
public string Title { get; set; }
}
/// <summary>
/// Company Virtual Properties
/// </summary>
public partial class Company
{
public virtual ICollection<Cartable> Cartables { get; } = new HashSet<Cartable>();
}
这是我的DTO
public class CompanyDTO : CoreDTO
{
public string Title { get; set; }
}
此方法返回具有记录的List<Company>
,然后我使用map获取一个List<CompanyDTO>
,然后为其空。
using static BaseMapper<Company, CompanyDTO>;
public Response<List<CompanyDTO>> GetAll(Guid currentUserId, int pageNum, int pageSize)
{
var ProcessResponse = new Response<List<CompanyDTO>>();
try
{
var entities = _unitOfWork.Companies.Query().OrderBy(x => x.Title).Skip(pageNum * pageSize).Take(pageSize).ToList();
ProcessResponse.Result = Map(entities); //it turns out null here.
ProcessResponse.RecCount = _unitOfWork.Companies.Query().Count();
}
catch (Exception ex)
{
ProcessResponse.Failed(ex.Message, ex.InnerException.Message);
}
return ProcessResponse;
}
答案 0 :(得分:1)
您需要为实体类型而不是集合类型进行映射。 即
new MapperConfiguration(cfg => cfg.CreateMap<TD, T>());
代替
new MapperConfiguration(cfg => cfg.CreateMap<List<TD>, List<T>>());
然后它将起作用。
P.S。 Automapper的文档非常好-您没有尝试阅读吗? https://docs.automapper.org/en/stable/Lists-and-arrays.html