简体   繁体   English

C#Automapper通用映射

[英]C# Automapper Generic Mapping

When playing around with AutoMapper I was wondering whether the following is possible to implement like this (haven't been able to set it up correctly). 当与AutoMapper一起玩时,我想知道是否可以实现以下这样的功能(无法正确设置)。

Base Service: 基本服务:

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

Concrete Service: 具体服务:

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

Current mappings: 当前映射:

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

I'm kindly clueless on how the mapping should be done. 我对如何完成映射一无所知。 Anyone any advice or is this just not the way to go? 任何人的建议还是这不是路吗?

You can specify DTO type in BaseService as generic parameter: 您可以在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());
    }
}

Managed to solve my problem with the following line of code which looks up the mapping of the passed entity to the basecontroller. 通过以下代码行设法解决了我的问题,该行代码查找了传递的实体到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