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

女生的网名这么多〃 提交于 2019-12-07 15:41:11

问题


I'm using Entity Framework 6 and Automapper to map entities to dtos.

I have this models

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

I use automapper Queryable Extension to map dto from entity.

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

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?


回答1:


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

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

Then at runtime:

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

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



来源:https://stackoverflow.com/questions/31751531/is-it-possible-to-tell-automapper-to-ignore-mapping-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!