'AutoMapper unflattening with naming convention results in null object
I'm using AutoMapper 11.0.0 to map an DTO to another class.
My goal is to map SupplierDto.CreatedById and SupplierDto.CreatedByName to Supplier.CreatedBy.Id and Supplier.CreatedBy.Name.
Reading the docs, I found that AutoMapper has an unflattening feature which uses PascalCase naming conventions to map source to destiny objects without the need of mapping member by member.
The thing is that I'm missing something, because my classes are named with the convention, and I'm getting null objects.
Here are my classes:
Supplier.cs
public class Supplier
{
public long Id { get; set; }
public string Name { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime? UpdatedAt { get; set; }
public User CreatedBy { get; set; }
public User UpdatedBy { get; set; }
}
User.cs
public class User
{
public long Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
SupplierDto.cs
public class SupplierDto
{
public long Id { get; set; }
public string Name { get; set; }
public string Cnpj { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime? UpdatedAt { get; set; }
public long CreatedById { get; set; }
public string CreatedByName { get; set; }
}
Here is my code for mapping SupplierDto to Supplier:
var configuration = new MapperConfiguration(cfg =>
{
cfg.CreateMap<SupplierDto, Supplier>();
});
var mapper = new Mapper(configuration);
var dto = new SupplierDto
{
Id = 1,
Name = "Supplier One",
CreatedById = 2,
CreatedByName = "John Doe",
CreatedAt = DateTime.Now,
UpdatedAt = DateTime.Now,
};
var supplier = mapper.Map<Supplier>(dto);
//supplier.CreatedBy is null here
Console.WriteLine(supplier?.CreatedBy?.Name);
The result I'm trying to achieve is this:
var supplier = new Supplier {
Id = dto.Id,
Name = dto.Name,
CreatedAt = dto.CreatedAt,
UpdatedAt = dto.UpdatedAt,
CreatedBy = new User
{
Id = dto.CreatedById,
Name = dto.CreatedByName
}
}
AutoMapper does the map for Id, Name, CreatedAt and UpdatedAt props, but doesn't create a new User for CreatedBy prop.
What I am missing?
Solution 1:[1]
First, AM without configuration validation is difficult to use. So do that :)
Then, as the docs say, you need ReverseMap to unflatten.
c.CreateMap<Supplier, SupplierDto>().ForMember(d=>d.Cnpj, o=>o.Ignore()).ReverseMap();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Lucian Bargaoanu |
