c# - Entity Framework + AutoMapper(实体到 DTO 和 DTO 到实体)

标签 c# entity-framework automapper dto

我在将 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/

相关文章:

c# - 仅从 JSON 中删除

c# - ArgumentException 多个参数和嵌套参数的 ParamName 约定

entity-framework - 具有多个 Web 配置转换的 Entity Framework 迁移

c# - 我可以使用 AutoMapper 映射目标继承而不需要源继承吗?

c# - 什么是用于解析单个句子的正则表达式?

c# - LINQ 中字母数字数据的 SQL Order By 子句未按预期排序

c# - 标识为 'Id' 的项目已存在于元数据集合中。参数名称 : item

entity-framework - 什么是自有实体?何时以及为何在 Entity Framework Core 中使用拥有的实体?

Automapper:将 List<string> 映射到 List<Class>

c# - AutoMapper - 在没有 `set;` 实现的情况下映射属性