How does Include() work with LINQ expression syntax for eager loading?

c# entity-framework linq linqpad

Question

I have a query below, but I want to perform an Include() to eager load properties. Actions has a navigation property, User (Action.User)

1) My basic query:

from a in Actions
join u in Users on a.UserId equals u.UserId
select a

2) First attempt:

from a in Actions.Include("User")
join u in Users on a.UserId equals u.UserId
select a

But Action.User is not populated.

3) Try to eager load 'User' into the navigation property in action outside of query:

(from a in Actions
join u in Users on a.UserId equals u.UserId    
select a).Include("User")

In LINQPad trying Include's I get an error:

'System.Linq.IQueryable' does not contain a definition for 'Include' and no extension method 'Include' accepting a first argument of type 'System.Linq.IQueryable' could be found (press F4 to add a using directive or assembly reference)

I think this is because LINQ doesn't support Include().

So I tried in VS; query 2 runs, but returns unpopulated User property. Query 3 the extension method does not seem to exist, although it does exist on Action itself without the query.

1
33
7/21/2011 1:02:00 PM

Accepted Answer

I figured it out, thanks for the suggestions anyway. The solution is to do this (2nd attempt in my question):

var qry = (from a in Actions
join u in Users on a.UserId equals u.UserId    
select a).Include("User")

The reason intellisense didn't show Include after the query was because I needed the following using:

using System.Data.Entity;

Everything worked fine doing this.

61
7/21/2011 1:00:56 PM

Popular Answer

Better, refactor friendly code (EF6)

using System.Data.Entity;
[...]
var x = (from cart in context.ShoppingCarts
         where table.id == 123
         select cart).Include(t => t.CartItems);

or

var x = from cart in context.ShoppingCarts.Include(nameof(ShoppingCart.CartItems))
        where table.id == 123
        select cart;

Update 3/31/2017

You can also use include in lambda syntax for either method:

var x = from cart in context.ShoppingCarts.Include(p => p.ShoppingCart.CartItems))
        where table.id == 123
        select cart;


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow