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

shkipper picture shkipper · May 21, 2009 · Viewed 47.6k times · Source

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 !

Answer

Pablo Montilla picture Pablo Montilla · May 28, 2010

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.