是否可以告诉自动映射器在运行时忽略映射?

Is it possible to tell automapper to ignore mapping at runtime?

我正在使用 Entity Framework 6 和 Automapper 将实体映射到 dtos。

我有这个型号

public class PersonDto
{
    public int Id { get; set; }
    public string Name { get; set; }
    public AddressDto Address { get; set; }
}

public class AddressDto
{
    public int Id { get; set; }
    public string Street { get; set; }
    public string City { get; set; }
}

我使用 automapper Queryable Extension 从实体映射 dto。

var personDto = dbContext.People.Project().To<PersonDto>();

上述方法的问题在于它会使 EF 始终加载地址实体。我希望只有在我明确告诉他们使用 include(x => x.Address) 时才加载地址。如果我在 automapper 映射中指定 ignore(),地址将不会被加载。是否可以告诉 automapper 在运行时忽略地址 属性?我正在使用的 Automapper 可查询扩展不支持 "Condition or after map" 等所有功能。有什么解决方法吗?

您需要为 DTO 启用显式扩展。首先在您的配置中:

Mapper.CreateMap<Person, PersonDto>()
    .ForMember(d => d.Address, opt => opt.ExplicitExpansion());

然后在运行时:

dbContext.People.Project.To<PersonDto>(membersToExpand: d => d.Address);

"membersToExpand" 可以是目标成员的表达式列表,也可以是表示要扩展的 属性 名称的字符串值字典。