我在ASP.NETMVC5应用程序中使用AutoMapper 6.2.0.

当我通过控制器调用我的视图时,它会正确显示所有内容.但是,当我刷新该视图时,Visual Studio显示一个错误:

System.InvalidOperationException:‘映射器已初始化.每个应用程序域/进程必须调用Initialize一次.’

我只在一个控制器中使用AutoMapper.尚未在任何地方进行任何配置,也未在任何其他服务或控制器中使用AutoMapper.

我的控制器:

public class StudentsController : Controller
{
    private DataContext db = new DataContext();

    // GET: Students
    public ActionResult Index([Form] QueryOptions queryOptions)
    {
        var students = db.Students.Include(s => s.Father);

        AutoMapper.Mapper.Initialize(cfg =>
        {
            cfg.CreateMap<Student, StudentViewModel>();
        });
            return View(new ResulList<StudentViewModel> {
            QueryOptions = queryOptions,
            Model = AutoMapper.Mapper.Map<List<Student>,List<StudentViewModel>>(students.ToList())
        });
    }

    // Other Methods are deleted for ease...

控制器内的错误:

enter image description here

我的模型类:

public class Student
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public string CNIC { get; set; }
    public string FormNo { get; set; }
    public string PreviousEducaton { get; set; }
    public string DOB { get; set; }
    public int AdmissionYear { get; set; }

    public virtual Father Father { get; set; }
    public virtual Sarparast Sarparast { get; set; }
    public virtual Zamin Zamin { get; set; }
    public virtual ICollection<MulaqatiMehram> MulaqatiMehram { get; set; }
    public virtual ICollection<Result> Results { get; set; }
}

我的ViewModel类:

public class StudentViewModel
{
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }
    public string CNIC { get; set; }
    public string FormNo { get; set; }
    public string PreviousEducaton { get; set; }
    public string DOB { get; set; }
    public int AdmissionYear { get; set; }

    public virtual FatherViewModel Father { get; set; }
    public virtual SarparastViewModel Sarparast { get; set; }
    public virtual ZaminViewModel Zamin { get; set; }
}

推荐答案

刷新视图时,您正在创建StudentsController的一个新实例,并因此重新初始化映射器,导致错误消息"映射器已初始化".

Getting Started Guide

Where do I configure AutoMapper?

如果您使用的是静态映射器方法,那么每个AppDomain只能进行一次配置.这意味着放置配置代码的最佳位置是在应用程序启动中,比如全局.ASP的asax文件.NET应用程序.

设置此功能的一种方法是将所有映射配置放入静电方法中.

App_Start/AutoMapperConfig.cs:

public class AutoMapperConfig
{
    public static void Initialize()
    {
        Mapper.Initialize(cfg =>
        {
            cfg.CreateMap<Student, StudentViewModel>();
            ...
        });
    }
}

然后在Global.asax.cs中调用这个方法

protected void Application_Start()
{
    App_Start.AutoMapperConfig.Initialize();
}

现在,您可以(重新)在控制器操作中使用它.

public class StudentsController : Controller
{
    public ActionResult Index(int id)
    {
        var query = db.Students.Where(...);

        var students = AutoMapper.Mapper.Map<List<StudentViewModel>>(query.ToList());

        return View(students);
    }
}

Asp.net相关问答推荐

域名 + 子域名在IIS部署

asp.net、url 重写模块和 web.config

Server.Transfer 在执行子请求时抛出错误.如何解决?

带有 Web 套接字的 SignalR

VS2013发布Web部署任务失败文件正在使用中

是否可以使用 Membership API 更改用户名

如何使用 ASP.NET Identity 创建用户并获取新创建的 ID

如何从 web.config 中读取系统值并在 ASP.NET MVC C# 方法中使用

如何在 ASP.NET Web API 中使用非线程安全的 async/await API 和模式?

LINQ to Entities 无法识别 MVC 4 中的System.String ToString()方法

ASP.NET 上的 WebSockets 教程

在生产中使用 LocalDb 是否正常?

在 ApiController 中添加自定义响应头

如何在 asp net core api 中使用 Created(或 CreatedAtAction / CreatedAtRoute)

aspnet_compiler 发现错误版本的 System.Web.WebPages 1.0.0.0 而不是 2.0.0.0

将新行添加到数据表的顶部

*.csproj 中的 usevshostingprocess 是什么?

IIS url 重写角色,除了一些 url

~/ 等价于 javascript

无法使用 ip:port 访问 WEB API,但可以在 VS 调试模式下使用 localhost:port