Ivan-Mark Debono
Ivan-Mark Debono

Reputation: 16340

How to load nested entities without lazy loading in Entity Framework?

I have the following model:

public class Order 
{
    public int Id {get; set;}
    public int Number {get; set;}
    public virtual ICollection<OrderDetail> Details {get; set;}
}

public class OrderDetail
{
    public int Id {get; set;}
    public int OrderId {get; set;}
    public virtual Product Product {get; set;}
}

public class Product
{
    public int Id {get; set;}
    public int Number {get; set;}
    public string Description {get; set;}
}

In my OrderRepository, I load a complete order like this:

public override Order Get(int id)
{
    return base.Get(id, x => x.Details);
}

And the base method is:

public virtual T Get(int id, params Expression<Func<T, object>>[] include)
{
    if (include.Any())
    {
        var set = include.Aggregate<Expression<Func<T, object>>, IQueryable<T>>
                  (dbSet, (current, expression) => current.Include(expression));

        return set.SingleOrDefault<T>(x => x.Id == id);
    }

    return dbSet.Find(id);
}

The above works partially fine because it loads the Order and the OrderDetails. However, I also want to load the related Product for every Detail so that I can display the product description in the list too.

How can I improve on the above method to allow me to do so?

Upvotes: 1

Views: 388

Answers (1)

haim770
haim770

Reputation: 49133

Just add another argument with nested Select:

public override Order Get(int id)
{
    return base.Get(id, x => x.Details, x => x.Details.Select(z => z.Product));
}

See MSDN

Upvotes: 1

Related Questions