7

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?

Reynaldi
  • 1,125
  • 2
  • 19
  • 41
  • 1
    Why not create a different PersonDto w/o Address. – scottheckel Jul 31 '15 at 17:09
  • Those are simplified models. My real models may have more than 3 properties like that. I would be a pain to create separate model for each scenario. – Reynaldi Jul 31 '15 at 17:25
  • @Reynaldi, it seems the Queryable Extension eager loads the entities for you. I am not sure how this would work, but you could try turning off lazy loading, set your includes, then call the Project() method. – DDiVita Aug 01 '15 at 14:12

1 Answers1

7

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.

Jimmy Bogard
  • 26,045
  • 5
  • 74
  • 69
  • But can i still use normal mapping with mapper.map? – Reynaldi Aug 03 '15 at 16:22
  • Your question says Projections - those two features aren't interchangeable in AutoMapper. – Jimmy Bogard Aug 03 '15 at 17:42
  • 1
    What do i do if i have more than one memberToExpand? I cannot do this: membersToExpand: d => new {d.Address, d.Address2}. And is it possible to expand child entity. eg. membersToExpand: d => d.Address.Select(x => x.Country) ? – Reynaldi Aug 12 '15 at 05:57