具有继承功能的 Automapper 5.2 不起作用

Automapper 5.2 with inheritance not working

我有一个实体:

public abstract class BaseEntity
{
     public Int16 Id { get; set; }
     public DateTime Timestamp { get; set; }
}

public class Certificate : BaseEntity
{
    public String Name { get; set; }
    public String Authority { get; set; }
    public DateTime RecieveDate { get; set; }
    public String Image { get; set; }
}

我有一个 ViewModel:

public abstract class BaseViewModel
{
    public Int16 Id { get; set; }
    public DateTime Timestamp { get; set; }
}

public class Certificate : BaseViewModel
{
    public String Name { get; set; }
    public String Authority { get; set; }
    public DateTime RecieveDate { get; set; }
    public String Image { get; set; }
}

我需要将 Entity.Certificate 映射到 ViewModel.Certificate(我根本不需要映射 BaseEntity,我想摆脱它)。 我有 Mapper 配置文件:

 public class MappingProfile : Profile
 {
    public MappingProfile()
    {
        CreateMap<Storage.Entities.Entities.BaseEntity, ViewModels.ViewModels.BaseViewModel>()
            .Include<Storage.Entities.Entities.Certificate, ViewModels.ViewModels.Certificate>();
        CreateMap<Storage.Entities.Entities.Certificate, ViewModels.ViewModels.Certificate>();
    }
 }

在 ConfigureServices 中注册:

services.AddAutoMapper();

上面提到的所有 3 类 都在不同的项目中(如果它有意义的话)。

这是控制器构造函数:

    private readonly Storage.Abstractions.Core.IStorage _storage;
    private readonly IMapper _mapper;
    public CertificateController(Storage.Abstractions.Core.IStorage storage, IMapper mapper)
    {
        this._storage = storage;
        this._mapper = mapper;
    }

以及我将实体映射到 viewModel 的获取方法:

   IEnumerable<Storage.Entities.Entities.Certificate> certificates = await this._storage.GetRepository<ICertificateRepository>().AllAsync();
   IEnumerable<ViewModels.ViewModels.Certificate>result = _mapper.Map<IEnumerable<Storage.Entities.Entities.Certificate>, IEnumerable<ViewModels.ViewModels.Certificate>>(certificates);

看起来正确,对吧? 但是:

映射类型错误。

映射类型: IEnumerable1 -> IEnumerable1 System.Collections.Generic.IEnumerable1[[AlexanderTsema.Storage.Entities.Entities.Certificate, AlexanderTsema.Storage.Entities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] -> System.Collections.Generic.IEnumerable1[[AlexanderTsema.ViewModels.ViewModels.Certificate, AlexanderTsema.ViewModels, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]

和内部执行: 缺少类型映射配置或不支持的映射。

映射类型: 证书 -> 证书 AlexanderTsema.Storage.Entities.Entities.Certificate -> AlexanderTsema.ViewModels.ViewModels.Certificate

请指教

我尝试将 Entity.Certificate 映射到 Entity.Certificate,它工作正常。

我认为您可能缺少的是 AutoMapper 可用于发现配置文件的至少一种类型或程序集。

services.AddAutoMapper(typeof(MappingProfile)); 应该可以解决问题。