AutoMapper.dll中发生了System.InvalidOperationException.附加信息:Mapper未初始化

w00*_*977 1 c# automapper asp.net-mvc-4

我用来发现AutoMapper非常简单易用.我正在努力使用新版本.我有两种类型:

namespace VehicleMVC.Models
{
    public class CarModel
    {
        public int id { get; set; }
        public string make { get; set; }
        public string model { get; set; }

    }
}
Run Code Online (Sandbox Code Playgroud)

和:

namespace Business
{
    public class Car
    {

        private int _id;
        private string _make;
        private string _model;

        public int id
        {
            get { return _id; }
            set { _id = value; }
        }

        public string make
        {
            get { return _make; }
            set { _make = value; }
        }

        public string model
        {
            get { return _model; }
            set { _model = value; }
        }

    }  
}
Run Code Online (Sandbox Code Playgroud)

我在CarController中试过这个:

public CarController()
        {
            service = new Service.Service();
            //Mapper.Initialize(cfg => cfg.CreateMap<Business.Car,CarModel>());
            //Mapper.Initialize(cfg => cfg.CreateMap<List<CarModel>, List<Business.Car>>());
            var config = new MapperConfiguration(cfg =>
                {
                    cfg.CreateMap<Business.Car, CarModel>();
            }       );
            config.AssertConfigurationIsValid();

        }

private CarModel getCarModel(Business.Car BusinessCar)
        {
            CarModel CarModel = AutoMapper.Mapper.Map<CarModel>(BusinessCar);
            return CarModel;
        }
Run Code Online (Sandbox Code Playgroud)

我得到的错误是:类型异常'System.InvalidOperationException' occurred in AutoMapper.dll. Additional information: Mapper not initialized. Call Initialize with appropriate configuration.但未在用户代码中处理.怎么了?

stu*_*rtd 5

创建配置后,必须使用它初始化映射器:

var config = new MapperConfiguration(cfg =>
{
     cfg.CreateMap<Business.Car, CarModel>();
};

config.AssertConfigurationIsValid();
Mapper.Initialize(config);
Run Code Online (Sandbox Code Playgroud)