Reputation: 149
In a .NET 6 n-tier application, I would like to map DTO models to ORM models via AutoMapper. Because of the way how my ORM is set up, it is important that the destination object does not change instance. When I map via _mapper.Map(source, destination)
instead of _mapper.Map<TDestination>(source)
, null child objects are not overwritten in destination.
An example:
Let's say I have the following DTO models defined:
public class DummyDto
{
public ChildDto Child { get; set; }
public ChildDto Child2 { get; set; }
}
public class ChildDto
{
public string SomeValue { get; set; }
}
And the following ORM models defined:
public class Dummy
{
public Child Child { get; set; }
public Child Child2 { get; set; }
}
public class Child
{
public string SomeValue { get; set; }
}
Next, I set up the following ORM model:
var dummyOrm = new Dummy()
{
Child = new Child()
{
SomeValue = "Foo",
},
Child2 = new Child()
{
SomeValue = "Baz",
},
}
And the following DTO model:
var dummyDto = new DummyDto()
{
Child = new ChildDto()
{
SomeValue = "updated",
},
Child2 = null,
}
Afterwards, I automap from DTO to ORM:
_mapper.Map(dummyDto, dummyOrm);
And I can see that the AutoMapper default behavior has ignored null
child object from DTO and the dummyOrm looks like this:
{
"Child": {
"SomeValue": "updated",
},
"Child2": {
"SomeValue": "Baz",
}
}
While I'd like it to see Child2 overwritten with null
{
"Child": {
"SomeValue": "updated",
},
"Child2": null
}
I have found an option how to workaround this via AfterMap
, but I was wondering if somehow I can configure my mapper via MapperConfiguration
to have this as the default behavior everywhere?
Upvotes: 0
Views: 425
Reputation: 149
Turns out it was a bug in AutoMapper and updating AutoMapper to 12.0.1 pre-release fixed the issue.
Upvotes: 1