我正在使用 Automapper 在 Entity 和 ViewModel 对象之间进行映射(双向)。该模型使用 EF4 DbContext POCO,需要启用 LazyLoading(因此需要代理生成)。
我在尝试从视图模型更新现有实体时遇到了问题。当我调用 Mapper.Map(vm, entity) 时,Automapper 会引发异常。我的问题是:您应该如何使用 Automapper 处理 EF 代理对象?
代码看起来(简化)如下:
public class MyEntity
{
public int Id {get;set;}
public int Name {get;set;}
}
public class ViewModel
{
public int Id {get;set;}
public int Name {get;set;}
}
Mapper.CreateMap<MyEntity, ViewModel>();
Mapper.CreateMap<ViewModel, MyEntity>();
public ActionResult Edit(ViewModel vm)
{
MyEntity entity = db.MyEntities.Find(vm.Id);
Mapper.Map(vm, entity);
db.Entry(entity).State = EntityState.Modified;
db.SaveChanges();
}
当我调用 Mapper.Map(vm, entity) 来更新现有的实体对象时,我得到了异常:
'Mapper.Map(viewModel, resultSet)' threw an exception of type 'AutoMapper.AutoMapperMappingException'
base {System.Exception}: {"Missing type map configuration or unsupported mapping.\n\nMapping types:\r\nResultSetView -> ResultSet_692D75838D4DC59B922F3E88CF1B10516CBF6CD8A32C4BE2F3FCC28CE83F0BD2\r\nSciensus.Applications.ClinicalStudies.Web.Areas.Patient.Models.ResultSetView -> System.Data.Entity.DynamicProxies.ResultSet_692D75838D4DC59B922F3E88CF1B10516CBF6CD8A32C4BE2F3FCC28CE83F0BD2\n\nDestination path:\nResultSet_692D75838D4DC59B922F3E88CF1B10516CBF6CD8A32C4BE2F3FCC28CE83F0BD2\n\nSource value:\nSciensus.Applications.ClinicalStudies.Web.Areas.Patient.Models.ResultSetView"}
Context: {Trying to map ResultSetView to ResultSet_692D75838D4DC59B922F3E88CF1B10516CBF6CD8A32C4BE2F3FCC28CE83F0BD2.}
Message: "Missing type map configuration or unsupported mapping.\n\nMapping types:\r\nResultSetView -> ResultSet_692D75838D4DC59B922F3E88CF1B10516CBF6CD8A32C4BE2F3FCC28CE83F0BD2\r\nSciensus.Applications.ClinicalStudies.Web.Areas.Patient.Models.ResultSetView -> System.Data.Entity.DynamicProxies.ResultSet_692D75838D4DC59B922F3E88CF1B10516CBF6CD8A32C4BE2F3FCC28CE83F0BD2\n\nDestination path:\nResultSet_692D75838D4DC59B922F3E88CF1B10516CBF6CD8A32C4BE2F3FCC28CE83F0BD2\n\nSource value:\nSciensus.Applications.ClinicalStudies.Web.Areas.Patient.Models.ResultSetView"
StackTrace: ""