I am using Automapper to map between Entity and ViewModel object (in both directions). The model uses EF4 DbContext POCOs and needs LazyLoading (and therefore Proxy Generation) enabled.
I have come across a problem attempting to update an existing entity from a viewmodel. When I call Mapper.Map(vm, entity), Automapper throws an exception. My question is: how are you supposed to work with EF Proxy objects using Automapper?
The code looks (simplified) like this:
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();
}
When I call Mapper.Map(vm, entity) to update the existing entity object, I get the exception:
'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: ""