是否可以告诉automapper在运行时忽略映射

是否可以告诉automapper在运行时忽略映射

本文介绍了是否可以告诉automapper在运行时忽略映射?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using Entity Framework 6 and Automapper to map entities to 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; }
}

我使用自动映射器可查询扩展从实体映射dto.

I use automapper Queryable Extension to map dto from entity.

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

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

The problem with above method is that it will make EF to always load the address entity. I want address to be loaded only if i explicitly tell them to with include(x => x.Address). If i specify ignore() in automapper map, the address will not be loaded. Is it possible to tell automapper to ignore the address property at runtime? Automapper queryable extensions i'm using doesn't support all functionalities like "Condition or after map". Is there any workaround for this?

推荐答案

您需要为DTO启用显式扩展.首先是您的配置:

You need to enable explicit expansion for your DTOs. First in your configuration:

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

然后在运行时:

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

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

The "membersToExpand" can be a list of expressions to destination members, or a dictionary of string values representing the property names to expand.

这篇关于是否可以告诉automapper在运行时忽略映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 05:10