在ASP.NET Core中配置AutoMapper

时间:2019-01-24 10:15:24

标签: automapper asp.net-core-2.2 automapper-8

我正在尝试使用自动映射器8.0.0来填充WorkViewModel的列表。 该列表使用实体框架从Work类中将数据从数据库中移出。

由于投掷跟随错误,初始化似乎出了什么问题?

  

InvalidOperationException:映射器未初始化

我在做什么错了?

我已经设置了以下代码!

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

WorkViewModel:

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

1 个答案:

答案 0 :(得分:0)

仅将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软件包。