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

六眼飞鱼酱① 提交于 2019-11-27 04:12:44

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.

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");
K0D4

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;

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

I use for this the LoadWith option

var dataOptions = new System.Data.Linq.DataLoadOptions();
dataOptions.LoadWith<Action>(ac => as.User);
ctx.LoadOptions = dataOptions;

Thats it. ctx is your DataContext. This works for me :-)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!