How does LINQ expression syntax work with Include() for eager loading
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.
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;
If what you want is a query that will return all Action
entities whose associated User
entity actually exists via the Action.UserId
foreign key property, this will do it:
var results = context.Actions
.Include("User")
.Where(action =>
context.Users.Any(user =>
user.UserId == action.UserId));
However you don't have to use foreign key properties in order to do filtering, since you also have navigation properties. So your query can be simplified by filtering on the Action.User
navigation property instead, like in this example:
var results = context.Actions
.Include("User")
.Where(action => action.User != null);
If your model states that the Action.User
property can never be null (i.e. the Action.UserId
foreign key is not nullable in the database) and what you want is actually all Action
entities with their associated Users
, then the query becomes even simpler
var results = context.Actions.Include("User");
Doing the basic query mentioned in your posted question you won't be able to see the User properties unless you return an anonymous type as following:
from a in Actions
join u in Users on a.UserId equals u.UserId
select new
{
actionUserId = a.UserId
.
.
.
userProperty1 = u.UserId
};
However to use the Include method on the ObjectContext you could use the following:
Make sure you have LazyLoading off by using the following line:
entities.ContextOptions.LazyLoadingEnabled = false;
Then proceed by
var bar = entities.Actions.Include("User");
var foo = (from a in bar
select a);