【发布时间】:2016-07-14 15:35:35
【问题描述】:
我有两种类型。业务层之一:
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"}。怎么了?我已经标记了导致异常的行(倒数第三行)。
【问题讨论】:
-
cfg.CreateMap<Business.Car, Data.Car>().ForMember(c => c.facttables, option => option.Ignore()).ReverseMap()?我想这可能只适用于简单的地图。请记住,您必须在两个方向上定义映射才能在两个方向上获得地图(我总是忘记哪个是源哪个是目的地,而没有拉起文档) -
.ReverseMap()确实只适用于简单的映射。但是我认为这里的部分问题是映射是在Business.Car和Data.Car之间定义的,但正如错误消息所说,实际类型是System.Data.Entity.DynamicProxies.Car_70BD8401A87DAAD8F5F0EC35BCAE5C9E6EE2D6CB5A1AFCE296B313D8AD87D2E9,它是一个实体框架代理。除非 AutoMapper 更聪明地处理它,否则它将无法工作,因为它是不同的类型,并且您必须在映射之前通过投影断开实体与 EF 的连接。 -
@stuartd,谢谢。您如何“将实体与 EF 投影断开连接”?
-
@stuartd,你能提供一些代码吗?我花了几个小时研究这个问题,但我不知道问题出在哪里。
标签: c# entity-framework asp.net-mvc-4 automapper automapper-5