实体框架+ AutoMapper(实体到DTO和DTO到实体) [英] Entity Framework + AutoMapper ( Entity to DTO and DTO to Entity )
问题描述
我有使用EF与AutoMapper一些问题。 = /
I've got some problems using EF with AutoMapper. =/
例如:
我有2相关实体(Customers和Orders)
和他们DTO类:
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 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();
Mapper.CreateMap();
CustomerDTO custDTO = Mapper.Map(cust);
//but when i try to map back from DTO to Entity it fails with AutoMapperMappingException.
Mapper.Reset();
Mapper.CreateMap();
Mapper.CreateMap();
Customers customerModel = Mapper.Map(custDTO); // exception is thrown here
我是不是做错了什么?
Am I doing something wrong?
在此先感谢!
推荐答案
我已经是有关更新EntityCollection引用问题。 AutoMapper创建一个从DTO到实体映射时关系的新实例,并且不讨好EF
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.
什么解决我的问题是配置AutoMapper使用我EntityCollection性能目标值。你的情况:
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());
AM这样就不会创建一个新的EntityCollection实例,将使用至极来了与原有客户实体。
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.
这篇关于实体框架+ AutoMapper(实体到DTO和DTO到实体)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!