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

后端 未结 8 1245
逝去的感伤
逝去的感伤 2021-01-30 07:38

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 :

         


        
8条回答
  •  孤街浪徒
    2021-01-30 08:15

    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.

提交回复
热议问题