Automapper创建一个对象的2个实例 [英] Automapper creates 2 instances of one object

查看:41
本文介绍了Automapper创建一个对象的2个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Company 对象有一个 Employees 列表,而我的 Payroll 对象有一个 Employees 列表.

在我的DTO中,假设 company payroll 都共享 employee 的相同实例(只有一个雇员对象)./p>

当我使用AutoMapper映射它们时:

  var config = new MapperConfiguration(cfg => {cfg.CreateMap< DTOBusiness,Business>();cfg.CreateMap< DTOCompany,Company>();cfg.CreateMap< DTOPayRoll,PayRoll>();cfg.CreateMap< DTOEmployee,Employee>();});var business = config.CreateMapper().Map< Business>(dtoBusiness); 

因此将创建该员工对象的两个单独的实例,

  company.Employee!= payRoll.Employee 

它们的属性相同,但实例不同.

这使事情变得很尴尬,因为它们在DAL中是相同的对象(并且在业务层中必须是相同的对象).

我可以阻止AutoMapper创建同一对象的2个实例吗?

解决方案

您需要在地图上设置PreserveReferences.它是为您自动设置的,仅用于防止递归.我想这不是事实.文档.

My Company object has a list of Employees, and my Payroll object has a list of Employees.

In my DTO, let's say company and payroll both share the same instance of employee (there is only one employee object).

When I map them with AutoMapper:

        var config = new MapperConfiguration(cfg => {
            cfg.CreateMap<DTOBusiness, Business>();
            cfg.CreateMap<DTOCompany, Company>();
            cfg.CreateMap<DTOPayRoll, PayRoll>();
            cfg.CreateMap<DTOEmployee, Employee>();
        });

        var business = config.CreateMapper().Map<Business>(dtoBusiness);

Two separate instances of that employee object are created, therefore:

company.Employee != payRoll.Employee

They're identical in properties, but not the same instance.

This makes things very awkward, because these are the same object in the DAL (and need to be the same object in the business layer).

Can I prevent AutoMapper from creating 2 instances of the same object?

解决方案

You need to set PreserveReferences on your map. It is set automatically for you only to prevent recursion. That's not the case here I suppose. The docs.

这篇关于Automapper创建一个对象的2个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆