mercredi 29 octobre 2014

Eager loading nested entities


Vote count:

0




I have the following (kept really simple):



public class Customer
{
public int Id {get; set}
public IEnumerable<Reminder> Reminders {get; set}
public IEnumerable<Order> Orders {get; set}
}

public class Reminder
{
public int CustomerId {get; set}
public string Text {get; set}
}

public class Order
{
public int CustomerId {get; set}
public int CategoryId {get; set}
}

public class OrderDetails
{
public int OrderId {get; set}
public int ProductId {get; set}
}


I'm also using generic repository pattern, and I load entities with nested entities as follows:



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);
}


Using Linq, I would like to load a Customer, all his Reminders and all Orders having a particular CategoryId. So I'm trying to do like this:



var customer = customerRepository.Get(10, x => x.Reminders, x => x.Orders.Select(o => o.OrderDetails));


But the above loads everything. And if I do the following, an exception is thrown:



var customer = customerRepository.Get(10, x => x.Reminders, x => x.Orders.Where(c => c.CategoryId == categoryId).Select(o => o.OrderDetials));


So how can I actually return only those orders I need?



asked 2 mins ago







Eager loading nested entities

Aucun commentaire:

Enregistrer un commentaire