简体   繁体   English

Automapper asp.net核心控制器 - 映射器未初始化错误

[英]Automapper asp.net core Controller - Mapper Not Initialized Error

I have been looking at this document https://automapper.readthedocs.io/en/stable/Getting-started.html to try to configure automapper to take away the pain of some manual attribute mapping. 我一直在查看这个文档https://automapper.readthedocs.io/en/stable/Getting-started.html ,试图配置automapper来消除一些手动属性映射的痛苦。

I am coming up against the following error: 我遇到了以下错误:

Message: System.InvalidOperationException : Mapper not initialized. 消息:System.InvalidOperationException:Mapper未初始化。 Call Initialize with appropriate configuration. 使用适当的配置调用Initialize。 If you are trying to use mapper instances through a container or otherwise, make sure you do not have any calls to the static Mapper.Map methods, and if you're using ProjectTo or UseAsDataSource extension methods, make sure you pass in the appropriate IConfigurationProvider instance. 如果您尝试通过容器或其他方式使用映射器实例,请确保您没有对静态Mapper.Map方法的任何调用,并且如果您使用的是ProjectTo或UseAsDataSource扩展方法,请确保传入适当的IConfigurationProvider实例。

This bit - "Mapper not initialized. Call Initialize with appropriate configuration" - is concerning because I feel I have done that in my startup.cs file. 这个位 - “Mapper未初始化。使用适当的配置调用Initialize” - 令人担忧,因为我觉得我已经在startup.cs文件中完成了这一操作。

I have the following controller action: 我有以下控制器操作:

[HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Index(NewCreditCardApplicationDetails applicationDetails)
    {
        if (!ModelState.IsValid)
        {
            return View(applicationDetails);
        }

        CreditCardApplication creditCardApplication = Mapper.Map<CreditCardApplication>(applicationDetails);

        //var creditCardApplication = new CreditCardApplication
        //{
        //    FirstName = applicationDetails.FirstName,
        //    LastName = applicationDetails.LastName,
        //    Age = applicationDetails.Age.Value,
        //    GrossAnnualIncome = applicationDetails.GrossAnnualIncome.Value,
        //    FrequentFlyerNumber = applicationDetails.FrequentFlyerNumber
        //};

        await _applicationRepository.AddAsync(creditCardApplication);

        return View("ApplicationComplete", creditCardApplication);
    }

The commented lines represent code that did work, but I want to remove. 注释行表示确实有效的代码,但我想删除。

My configure method in startup.cs file in my asp.net core web app looks like this: 我的asp.net核心web应用程序中的startup.cs文件中的配置方法如下所示:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, AppDbContext dbContext)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();

            dbContext.Database.EnsureCreated();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();

        Mapper.Initialize(cfg =>
        {
            cfg.CreateMap<NewCreditCardApplicationDetails, CreditCardApplication>();
        });

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

NewCreditCardApplicationDetails.cs looks like this: NewCreditCardApplicationDetails.cs如下所示:

public class NewCreditCardApplicationDetails
{
    [Display(Name = "First Name")]
    [Required(ErrorMessage = "Please provide a first name")]
    public string FirstName { get; set; }

    [Display(Name = "Last Name")]
    [Required(ErrorMessage = "Please provide a last name")]
    public string LastName{ get; set; }

    [Display(Name = "Age (in years)")]
    [Required(ErrorMessage = "Please provide an age in years")]
    [Range(18,int.MaxValue, ErrorMessage = "You must be at least 18 years old")]
    public int? Age { get; set; }

    [Display(Name = "Gross Income")]
    [Required(ErrorMessage = "Please provide your gross income")]        
    public decimal? GrossAnnualIncome { get; set; }
    public string FrequentFlyerNumber { get; set; }
}

CreditCardApplication.cs looks like this: CreditCardApplication.cs看起来像这样:

public class CreditCardApplication
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    public decimal GrossAnnualIncome { get; set; }
    public string FrequentFlyerNumber { get; set; }
}

Can anyone see what the issue is please? 任何人都可以看到问题是什么?

Thanks. 谢谢。

Checkout this: https://medium.com/ps-its-huuti/how-to-get-started-with-automapper-and-asp-net-core-2-ecac60ef523f 结帐: https//medium.com/ps-its-huuti/how-to-get-started-with-automapper-and-asp-net-core-2-ecac60ef523f

You should inject the mapper to use it and don't use the static one. 您应该注入映射器以使用它,而不要使用静态映射器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM