映射配置或不支持的映射

时间:2016-07-14 15:35:35

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

我有两种类型。一个在业务层:

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

    }

}

和数据层(实体框架)中的另一个:

namespace Data
{
    using System;
    using System.Collections.Generic;

    public partial class Car
    {
        public Car()
        {
            this.facttables = new HashSet<facttable>();
        }

        public int id { get; set; }
        public string make { get; set; }
        public string model { get; set; }

        public virtual ICollection<facttable> facttables { get; set; }
    }
}

以下是我从服务层获得的代码:

    namespace Data
{
    public class VehicleDAO : IVehicleDAO
    {

        private static readonly ILog log = LogManager.GetLogger(typeof(VehicleDAO));

        MapperConfiguration config;

        public VehicleDAO ()
        {
            Mapper.Initialize(cfg => cfg.CreateMap<Business.Car, Data.Car>());
            config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<Business.Car, Data.Car>()
                    .ForMember(dto => dto.facttables, opt => opt.Ignore());
                    //.ForMember(d => d.id, opt => opt.MapFrom(c => c.id))
                    //.ForMember(d => d.make, opt => opt.MapFrom(c => c.make))
                    //.ForMember(d => d.model, opt => opt.MapFrom(c => c.model));
            });
            config.AssertConfigurationIsValid();
        }

        public Data.Car Select(int id)
        {
            Data.Car car;
            using (VehicleEntities VehicleDatabase = new VehicleEntities())
            {
                car = VehicleDatabase.Cars.Where(c => c.id == id).ToList().Single();
                Business.Car cars = AutoMapper.Mapper.Map<Business.Car>(car);
            }
            return car;
        }

例外情况是:{"Missing type map configuration or unsupported mapping.\r\n\r\nMapping types:\r\nCar_70BD8401A87DAAD8F5F0EC35BCAE5C9E6EE2D6CB5A1AFCE296B313D8AD87D2E9 -> Car\r\nSystem.Data.Entity.DynamicProxies.Car_70BD8401A87DAAD8F5F0EC35BCAE5C9E6EE2D6CB5A1AFCE296B313D8AD87D2E9 -> Business.Car"}。怎么了?我已经标记了导致异常的行(从最后一行开始的第三行)。

1 个答案:

答案 0 :(得分:0)

自动映射器仅按照您创建映射的方向进行映射。创建地图<Business.Car, Data.Car&gt;创建从Business.Car到Data.Car的映射。看起来您正在尝试从Data.Car映射到Business.Car,这意味着您需要CreateMap <Data.Car, Business.Car>

Mapper.Initialize(cfg => cfg.CreateMap<Data.Car, Business.Car>());
config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<Data.Car, Business.Car>();
});
config.AssertConfigurationIsValid();