简体   繁体   中英

How to eagerly load nested entities in Entity Framework?

I have these models:

public class Category
{
    public int Id {get; set;}
    public string Name {get; set;}
    public virtual ICollection<CategoryProduct> Products {get; set;}
}

public class CategoryProduct
{
    public int Id {get; set;}
    public int CategoryId {get; set;}
    public int ProductId {get; set;}
    public virtual Category Category {get; set;}
    public virtual Product Product {get; set;}
}

public class Product
{
    public int Id {get; set;}
    public string Name {get; set;}
}

I'm loading a Category object and related Products by doing the following in the service layer:

categoryRepository.Get(x => x.Id == categoryId, x => x.Products);

And the corresponding generic repository method:

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

    return set.Where(predicate).FirstOrDefault();
}

To a certain extent, the above works fine because I can load one Cateory and corresponding Products with one SQL statement. However the Product property each CategoryProduct object is null .

How can I tell EF to also load each Product related to the CategoryProduct ?

Solved by doing:

categoryRepository.Get(x => x.Id == categoryId, 
                       x => x.Products.Select(p => p.Product));

This EF blog post helped a lot!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM