Alex Blanz
Alex Blanz

Reputation: 21

Automapper suddenly creates nested object

Entities:

public class Entity
{
    public int Id { get; set; }
}

public class User : Entity
{
    public string Name { get; set; }

    public Company Company { get; set; }
}

public class Company : Entity
{
    public string Name { get; set; }
}

Dto's:

public class EntityDto
{
    public int Id { get; set; }
}

public class UserDto : EntityDto
{
    public string Name { get; set; }

    public int? CompanyId { get; set; }
}

So I want to map User to UserDto like User.Company == null => UserDto.CompanyId == null and vice versa.

That is my Automapper configuration:

Mapper.Initialize(configuration =>
{
    configuration
        .CreateMap<User, UserDto>()
        .ReverseMap();
});

This works fine:

[Fact]
public void UnattachedUserMapTest()
{
    // Arrange
    var user = new User { Company = null };

    // Act
    var userDto = Mapper.Map<User, UserDto>(user);

    // Assert
    userDto.CompanyId.Should().BeNull();
}

but this test fails:

[Fact]
public void UnattachedUserDtoMapTest()
{
    // Arrange
    var userDto = new UserDto { CompanyId = null };

    // Act
    var user = Mapper.Map<UserDto, User>(userDto);

    // Assert
    user.Company.Should().BeNull();
}

Details:

Expected object to be <null>, but found 

Company
{
   Id = 0
   Name = <null>
}

Doesn't work for me:

...
.ReverseMap()
.ForMember(user => user.Company, opt => opt.Condition(dto => dto.CompanyId != null));

and well as that (just for example):

...
.ReverseMap()
.ForMember(user => user.Company, opt => opt.Ignore());

Why does Automapper create nested object and how can I prevent it?

Upvotes: 2

Views: 374

Answers (1)

Lucian Bargaoanu
Lucian Bargaoanu

Reputation: 3516

That "suddenly" bit is funny :)

configuration.CreateMap<User, UserDto>().ReverseMap().ForPath(c=>c.Company.Id, o=>o.Ignore());

You have a default MapFrom with CompanyId and that is applied in reverse. For details see this and a few other similar issues.

In the next version (on MyGet at the moment) you'll also be able to use

configuration.CreateMap<User, UserDto>().ReverseMap().ForMember(c=>c.Company, o=>o.Ignore());

Upvotes: 1

Related Questions