I'm using Automapper with EF Core. EF entities:
public class Team
{
public Guid? Id { get; set; }
public string Name { get; set; }
public Guid? OrganizationId { get; set; }
public Organization Organization { get; set; }
}
public class Organization
{
public Guid Id { get; set; }
public string Name { get; set; }
public ICollection<Team> Teams { get; set; }
}
And corresponding DTOs:
public class TeamDto
{
public Guid? Id { get; set; }
public string Name { get; set; }
public OrganizationDto Organization { get; set; }
}
public class OrganizationDto
{
public Guid? Id { get; set; }
public string Name { get; set; }
}
Type mappings:
cfg.CreateMap<Organization, OrganizationDto>();
cfg.CreateMap<TeamDto, Team>()
.ForMember(teamEntity => teamEntity.Organization, opt => opt.Ignore())
.ForMember(teamEntity => teamEntity.OrganizationId, opt => opt.MapFrom(
orgDto => orgDto == null ? null : orgDto.Id))
.ReverseMap();
When I try to map from Team entity -> dto, when Organization is null on Team entity, TeamDto has non null Organization property with null values. e.g.
var team = new Team
{
Name = "New Team"
};
// team.Organization is null as well as team.OrganizationId
var teamDto = s_mapper.Map<TeamDto>(team);
This is not desirable, as I want TeamDto's Organization property to be null.
I tried to configure this mapping via ForMember but it didn't take effect:
cfg.CreateMap<TeamDto, Team>()
.ForMember(teamEntity => teamEntity.Organization, opt => opt.Ignore())
.ForMember(teamEntity => teamEntity.OrganizationId, opt => opt.MapFrom(
orgDto => orgDto == null ? null : orgDto.Id))
.ReverseMap()
.ForMember(teamDto => teamDto.Organization, opt => opt.MapFrom(
teamEntity => teamEntity.Organization == null ? null : new OrganizationDto
{
Id = teamEntity.Organization.Id,
Name = teamEntity.Organization.Name
}));
How can I configure this to have Organization property be set to null when source is also null.
One way I can achieve this is by using AfterMap, but I'm looking for a solution that can be applied to all such cases without specifying AfterMap for each case.
AutoMapper v. 9.0.0
