防止 Automapper 使用空值创建对象 属性

Prevent Automapper creating object property with null values

我正在将 Automapper 与 EF Core 结合使用。 EF 实体:

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; }
}

以及相应的 DTO:

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; }
}

类型映射:

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();

当我尝试从团队实体 -> dto 进行映射时,当团队实体上的 Organization 为空时,TeamDto 具有非空 Organization 属性 和空值。例如

var team = new Team
{
    Name = "New Team"
};

// team.Organization is null as well as team.OrganizationId
var teamDto = s_mapper.Map<TeamDto>(team);   

这是不可取的,因为我希望 TeamDto 的 Organization 属性 为空。 我尝试通过 ForMember 配置此映射,但没有生效:

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
    }));

当源也为 null 时,如何将其配置为 Organization 属性 设置为 null。

实现此目的的一种方法是使用 AfterMap,但我正在寻找一种无需为每种情况指定 AfterMap 即可应用于所有此类情况的解决方案。

AutoMapper 9.0.0 版

有时 ReverseMap 只是碍事,这里似乎就是这种情况。您始终可以避免它并简单地显式创建反向映射。