问题
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