0

In my model, I have a User aggregate root, each of which has a collection of associated Transactions. Each Transaction has a reverse navigation property User.

I need to get all of the Transactions at once, and this has resulted in the following query in my UserRepository

public ICollection<ITransaction> GetAllTransactions() {

    return (from u in Set.Include("Transactions") 
            from t in u.Transactions
            select t).ToList();       
}

Set is IDbSet<User> from the EF context.

The problem is that lazy-loading is not implemented (nor do I want to implement it) and the Transaction.User property after querying is null. Everything is mapped through EF correctly.

What should the query be to retrieve all Transactions with a non-null User?

I am using EF6.

Graham
  • 1,497
  • 2
  • 16
  • 36
  • 1
    If you want the `User` property to be populated, then you need to `.Include("User")` on your transactions. Try `from t in u.Transactions.Include("User")` instead of `from t in u.Transactions`. – Maarten Feb 12 '16 at 13:59
  • Can you not just do something like `select new t, t.User` – markpsmith Feb 12 '16 at 14:01
  • Apologies, `Set` is `IDbSet` from the EF context – Graham Feb 12 '16 at 14:02
  • @mark no, you can't return an anonymous type from a non-dynamic method. – CodeCaster Feb 12 '16 at 14:02
  • @Maarten I tried that but I got a compile/intellisense error that `Include` cannot be resolved. `User.Transactions` is an `ICollection` – Graham Feb 12 '16 at 14:03
  • @Graham if you can't find `.Include`, make sure you have `using System.Data.Entity;` at the top of the repository.cs file. It's an extension method, so you need the namespace to use it. – danludwig Feb 12 '16 at 14:19
  • See [duplicate](http://stackoverflow.com/questions/10822656/entity-framework-include-multiple-levels-of-properties). It's either `Set.Include("Transactions").Include("Transactions.User")` or `Set.Include(s => s.Transactions).Include(s => s.Transactions.Select(t => t.User))`. – CodeCaster Feb 12 '16 at 14:21

1 Answers1

1

You need to actually Include the Transaction.User. It could be done after the final projection to Transaction like this

public ICollection<ITransaction> GetAllTransactions()
{    
    return Set.SelectMany(u => u.Transactions).Include(t => t.User).ToList();       
}
Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343