在 ASP.NET Core 中配置 AutoMapper

Configuring AutoMapper in ASP.NET Core

我正在尝试使用 automapper 8.0.0 来填充 WorkViewModel 的列表。 此列表使用 entity framework.

Work class 从数据库中获取数据

初始化似乎出了什么问题,因为抛出以下错误:

InvalidOperationException: Mapper not initialized

我做错了什么?

我设置了以下代码!

Startup.cs

services.AddAutoMapper();

正在调用的函数:

public async Task<IEnumerable<WorkViewModel>> GetAllAsync()
{
    IList<Work> works = await _context.Work.ToListAsync();

    IList<WorkViewModel> viewModelList = Mapper.Map<IList<Work>, IList<WorkViewModel>>(works);

    return viewModelList;
}

配置:

public class MappingProfile : Profile
{
    public MappingProfile()
    {
        Mapper.Initialize(cfg =>
        {
            cfg.CreateMap<WorkViewModel, Work>();
        });
    }
}

工作视图模型:

public class WorkViewModel
{
    public int WorkID { get; set; }
    public string Name { get; set; }
    public byte[] Tumbmail { get; set; }
    public string Discription { get; set; }

    public string Client { get; set; }
    public DateTime Date { get; set; }
    public string PreviewLink { get; set; }
    public string GitLink { get; set; }
    public string DownloadLink { get; set; }

    public int DetailID { get; set; }
    public byte[] Banner { get; set; }
    public string Documentation { get; set; }

    public int CategoryID { get; set; }
    public string Category { get; set; }
}

工作模式:

public class Work
{
    [Key]
    public int WorkID { get; set; }

    [Display(Name = "Project Name")]
    public string Name { get; set; }

    [Display(Name = "Client name")]
    public string Client { get; set; }

    [Display(Name = "Description")]
    public string Discription { get; set; }

    [Display(Name = "Date")]
    public DateTime Date { get; set; }

    [Display(Name = "Thumbmail")]
    public byte[] Tumbmail { get; set; }

    [Display(Name = "Preview Link")]
    public string PreviewLink { get; set; }

    [Display(Name = "Git Link")]
    public string GitLink { get; set; }

    [Display(Name = "DownloadLink")]
    public string DownloadLink { get; set; }


    public WorkCategory workCategory { get; set; }
    public WorkDetailed WorkDetailed { get; set; }
}

仅将 services.AddAutoMapper(); 添加到 ConfigureServices 方法对您不起作用。您必须按如下方式配置 AutoMapper

public void ConfigureServices(IServiceCollection services)
{
   // Auto Mapper Configurations
    var mappingConfig = new MapperConfiguration(mc =>
    {
        mc.AddProfile(new MappingProfile());
    });

    IMapper mapper = mappingConfig.CreateMapper();
    services.AddSingleton(mapper);

    services.AddMvc();
}

并且不要忘记安装 AutoMapper.Extensions.Microsoft.DependencyInjection nuget 包。