繁体   English   中英

C#Automapper通用映射

[英]C# Automapper Generic Mapping

当与AutoMapper一起玩时,我想知道是否可以实现以下这样的功能(无法正确设置)。

基本服务:

public class BaseService<T, IEntityDTO> : IService<T, IEntityDTO> where T : class, IEntity
{
    private IUnitOfWork _unitOfWork;
    private IRepository<IEntity> _repository;
    private IMapper _mapper;

    public BaseService(IUnitOfWork unitOfWork, IMapper mapper)
    {
        _unitOfWork = unitOfWork;
        _repository = unitOfWork.Repository<IEntity>();
        _mapper = mapper;
    }

    public IList<IEntityDTO> GetAll()
    {
        return _mapper.Map<IList<IEntityDTO>>(_repository.GetAll().ToList());
    }
}

具体服务:

public class HotelService : BaseService<Hotels, HotelsDTO>, IHotelService
{

    private IUnitOfWork _unitOfWork;
    private IRepository<Hotels> _hotelsRepository;
    private IMapper _mapper;

    public HotelService(IUnitOfWork unitOfWork, IMapper mapper) : base(unitOfWork, mapper)
    {
        _unitOfWork = unitOfWork;
        _hotelsRepository = unitOfWork.Repository<Hotels>();
        _mapper = mapper;
    }
}

当前映射:

public class AutoMapperProfileConfiguration : Profile
{
    protected override void Configure()
    {
        CreateMap<Hotels, HotelsDTO>().ReverseMap();
    }
}

我对如何完成映射一无所知。 任何人的建议还是这不是路吗?

您可以在BaseService中将DTO类型指定为通用参数:

public class BaseService<T, TDTO> : IService<T, TDTO> 
    where T : class, IEntity
    where TDTO : class, IEntityDTO
{
    private IRepository<T> _repository;
...
...
    public IList<TDTO> GetAll()
    {
        return _mapper.Map<IList<TDTO>>(_repository.GetAll().ToList());
    }
}

通过以下代码行设法解决了我的问题,该行代码查找了传递的实体到basecontroller的映射。

public List<TDTO> GetAll()
{
    var list = _repository.GetAll().ToList();
    return (List<TDTO>)_mapper.Map(list, list.GetType(), typeof(IList<TDTO>));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM