【问题标题】:Configuring AutoMapper in ASP.NET Core在 ASP.NET Core 中配置 AutoMapper
【发布时间】:2019-06-18 01:01:25
【问题描述】:

我正在尝试使用 automapper 8.0.0 来填充WorkViewModel 的列表。 此列表使用实体框架从数据库中获取来自 Work 类的数据。

由于引发以下错误,初始化看起来好像出了点问题:

InvalidOperationException:映射器未初始化

我做错了什么?

我已经设置了以下代码!

启动.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; }
}

【问题讨论】:

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2020-06-21
    • 1970-01-01
    • 2022-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-19
    相关资源
    最近更新 更多