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

时间:2016-07-14 14:29:03

标签: c# asp.net-mvc-4 automapper

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

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

    }
}

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

    }  
}

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

我得到的错误是:'System.InvalidOperationException' occurred in AutoMapper.dll. Additional information: Mapper not initialized. Call Initialize with appropriate configuration.类型的例外,但未在用户代码中处理。有什么问题?

1 个答案:

答案 0 :(得分:5)

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

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

config.AssertConfigurationIsValid();
Mapper.Initialize(config);