Prevent AutoMapper forecasts from forcibly downloading similar data

Is there a way to configure AutoMapper to follow the instructions for loading the .Include style for the Entity Framework?

I have disabled lazy loading for my context, and I want to conditionally load related data for certain objects. Ideally, I would like to do this using the include syntax. Sort of:

if(loadAddreses)
{
    query = query.Include(e => e.Addresses);
}

if(loadEmails)
{
    query = query.Include(e => e.Emails);
}

The problem is that AutoMapper sees that the model I'm designing includes Addresses and E-mail and generates SQL that loads all this data, regardless of what I asked to enable EF. In other words:

var model = query.Project.To<MyModel>();

If MyModel has a collection of addresses, it will load the addresses regardless of my Include instructions.

, , , ? , , .

+4
1

, , . , AutoMapper 3.3.0-ci1027 ( ).

, :

public class Address
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int AddressId { get; set; }
    public string Text { get; set; }
}

public class Email
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int EmailId { get; set; }
    public string Text { get; set; }
}

public class User
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public virtual ICollection<Address> Addresses { get; set; }
    public virtual ICollection<Email> Emails { get; set; }

    public User()
    {
        this.Addresses = new List<Address>();
        this.Emails = new List<Email>();
    }
}

, , .

User UserViewModel :

Mapper.CreateMap<User, UserViewModel>()
    .ForMember(x => x.Emails, opt => opt.ExplicitExpansion())
    .ForMember(x => x.Addresses, opt => opt.ExplicitExpansion());

:

var viewModels = context.Set<User>().Project()
    .To<UserViewModel>(new { }, u => u.Emails).ToList();

Emails. opt => opt.ExplicitExpansion() , , , To. ( ) , ( Emails).

, , - Include, , , To, , , - .

+5

All Articles