FBryant87
FBryant87

Reputation: 4595

Automapper creates 2 instances of one object

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?

Upvotes: 0

Views: 546

Answers (1)

Lucian Bargaoanu
Lucian Bargaoanu

Reputation: 3516

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.

Upvotes: 2

Related Questions