Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 !

like image 869
shkipper Avatar asked May 21 '09 09:05

shkipper


People also ask

How do I use AutoMapper in Entity Framework?

To use AutoMapper first install NuGet. Then, install AutoMapper from the package manager console: PM> Install-Package AutoMapper.

Is AutoMapper faster than manual mapping?

Inside this article, it discusses performance and it indicates that Automapper is 7 times slower than manual mapping. This test was done on 100,000 records and I must say I was shocked.

How does AutoMapper work in C#?

AutoMapper in C# is a library used to map data from one object to another. It acts as a mapper between two objects and transforms one object type into another. It converts the input object of one type to the output object of another type until the latter type follows or maintains the conventions of AutoMapper.


2 Answers

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.

like image 101
Pablo Montilla Avatar answered Sep 25 '22 04:09

Pablo Montilla


Try mapping to an existing object:

entity = Mapper.Map<MyDTO, NyEntity>(dto, entity);  

And keep the Ignore()'s in place.

http://groups.google.com/group/automapper-users/browse_thread/thread/24a90f22323a27bc?fwc=1&pli=1

like image 41
ishakkulekci Avatar answered Sep 24 '22 04:09

ishakkulekci