Alex Rivera | Logout

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

Asked 2009-05-21T09:03:53.630
23

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 !

Edit
Report

2 Answers

2

AutoMapper is very expressive when it comes to mapping error. read the exception message carefully.

another important thing is to remember to call Mapper.AssertConfigurationIsValid(); after creating the mappings. it gives an error if the mapping is wrong, thus preventing an exception later in the application runtime.

answered 2009-10-18T17:09:50.327
2

You should ignore mapping of some entity properties like so:

Mapper.CreateMap<CustomerDto, Customer>()
                .ForMember(dest => dest.EntityKey, opt => opt.Ignore())
                .ForMember(dest => dest.Licenses, opt => opt.Ignore())
                .ForMember(dest => dest.AccessCodes, opt => opt.Ignore());

If you examine the message from the exception thrown by Automapper, you should see the entity properties that cannot be mapped and ignore them as above.

answered 2011-10-07T15:29:42.503

Your Answer