Henrik
Henrik

Reputation: 63

AutoMapper creates empty objects instead of null

I recently upgraded AutoMapper from 6.0.2 to 6.1.1 and got a problem:

public class Entity1
{
    public Entity2 MyEntity2 { get; set; } // Entity2 is a class
    public Guid MyEntity2Id { get;set; }
    // Other parameters...
}

public class ViewModel1
{
    Guid Entity1Id { get; set; }
    // Other parameters...
}

The mapping:

cfg.CreateMap<Entity1, ViewModel1>.ReverseMap();

With version 6.0.2:

var myEntity1 = Mapper.Map<Entity1>(viewModel1);

after this mapping myEntity1.MyEntity2 is null.

After upgrading to v 6.1.1 I run exactly the same mapping but myEntity1.MyEntity2 is an empty Entity2 object and this creates a lot of problems.

Can anyone tell me how to change the mapping so myEntity1.MyEntity2 is null after the mapping?

Upvotes: 4

Views: 774

Answers (1)

Eternal21
Eternal21

Reputation: 4664

I hit the same problem today. After a bit of research, I found the following page: https://github.com/AutoMapper/AutoMapper/issues/2693

The culprit was ReverseMap(). Once you remove that call, Automapper starts working correctly (null source creates null destination object, instead of an empty object). So in your case you would have to replace this:

cfg.CreateMap<Entity1, ViewModel1>.ReverseMap();

with this:

cfg.CreateMap<Entity1, ViewModel1>();
cfg.CreateMap<ViewModel1, Entity1>();

Upvotes: 1

Related Questions