【问题标题】:C# Automapper Generic MappingC# Automapper 通用映射
【发布时间】:2016-09-13 09:07:30
【问题描述】:

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

我不知道应该如何进行映射。任何人有任何建议,或者这不是要走的路吗?

【问题讨论】:

  • 不清楚你在问什么。你到底有什么问题?
  • 我更新了代码以使其清晰。我正在尝试实现通用映射,我可以根据传递给我的基本服务的内容,对我的具体类型进行映射。
  • 我想为我的所有具体服务编写一些通用的东西,以便映射自动进行。否则我不得不将 getall 方法放到我的具体服务中。所以我必须以具体的方式处理映射。例如:_mapper.Map>(_repository.GetAll().ToList());

标签: c# automapper-5


【解决方案1】:

您可以在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());
    }
}

【讨论】:

  • 感谢您的回复,但这并没有改变大小写。问题是 Automapper 试图映射我试图避免的 IEntity。我希望完成从 Hotel 到 HotelDTO 的映射,而不是从 IEntity 到 IEntityDTO。我想使用 IEntity 和 IEntityDTO 作为具体类型的占位符,以便可以在通用基础服务中完成映射。
  • 只使用具体类型而不是接口(@98​​7654323@ 和Map&lt;IList&lt;TDTO&gt;&gt;
  • 如果你想使用接口,泛型有什么意义?
  • 您对泛型的看法是正确的。我想念你的意思。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-13
    • 2013-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多