我在将 EF 与 AutoMapper 结合使用时遇到了一些问题。 =/
例如:
我有 2 个相关实体(客户和订单) 他们是 DTO 类:
class CustomerDTO { public string CustomerID {get;set;} public string CustomerName {get;set;} public IList< OrderDTO > Orders {get;set;} }<p></p> <p>class OrderDTO { public string OrderID {get;set;} public string OrderDetails {get;set;} public CustomerDTO Customers {get;set;} }</p> <p>//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);</p>
//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
我做错了什么吗?
提前致谢!
最佳答案
我遇到的问题与 EntityCollection 引用的更新有关。当从 DTO 映射到实体时,AutoMapper 会创建一个新的关系实例,这不会让 EF 满意。
解决我问题的方法是将 AutoMapper 配置为使用我的 EntityCollection 属性的目标值。在你的情况下:
Mapper.CreateMap< CustomerDTO , Customers >().ForMember(c => c.Orders, o => o.UseDestinationValue());
这样 AM 就不会创建新的 EntityCollection 实例,而是使用原始 Customer 实体附带的实例。
我仍在努力寻找一种自动化方法,但现在它解决了我的问题。
关于c# - Entity Framework + AutoMapper(实体到 DTO 和 DTO 到实体),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/891999/