AutoMapper + Entity Framework ( Entity to DTO and DTO to Entity )

automapper c# dto entity-framework


I've got some problems using EF with AutoMapper. =/

for example :

I've got 2 related entities ( Customers and Orders ) and they're DTO classes :

class CustomerDTO
   public string CustomerID {get;set;}
   public string CustomerName {get;set;}
   public IList< OrderDTO > Orders {get;set;}

class OrderDTO { public string OrderID {get;set;} public string OrderDetails {get;set;} public CustomerDTO Customers {get;set;} }

//when mapping Entity to DTO the code works Customers cust = getCustomer(id); Mapper.CreateMap< Customers, CustomerDTO >(); Mapper.CreateMap< Orders, OrderDTO >(); CustomerDTO custDTO = Mapper.Map(cust);

//but when i try to map back from DTO to Entity it fails with AutoMapperMappingException. Mapper.Reset(); Mapper.CreateMap< CustomerDTO , Customers >(); Mapper.CreateMap< OrderDTO , Orders >(); Customers customerModel = Mapper.Map< CustomerDTO ,Customers >(custDTO); // exception is thrown here

Am I doing something wrong?

Thanks in Advance !

11/9/2011 11:56:18 PM

Popular Answer

The problem I had was related to updates to EntityCollection references. AutoMapper creates a new instance of the relation when mapping from the DTO to the Entity, and that doesn't please the EF.

What solved my problem was configuring AutoMapper to use the destination value for my EntityCollection properties. In your case:

Mapper.CreateMap< CustomerDTO , Customers >().ForMember(c => c.Orders, o => o.UseDestinationValue());

That way AM will not create a new EntityCollection instance, and will use that wich came with the original Customer entity.

I'm still working for a way to automate this, but for now it solves my problem.

5/28/2010 5:59:19 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow