LINQ表达式语法如何与Include()一起用于预先加载

我在下面有一个查询,但我想对eager load属性执行Include()。 Actions有一个导航属性,User(Action.User)

1)我的基本查询:

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

2)第一次尝试:

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

但是没有填充Action.User。

3)尝试将’User’加载到查询之外的导航属性中:

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

在LINQPad尝试包含的我得到一个错误:

‘System.Linq.IQueryable’不包含’Include’的定义,也没有扩展方法’Include’接受类型’System.Linq.IQueryable’的第一个参数可以找到(按F4添加using指令或程序集引用)

我认为这是因为LINQ不支持Include()。

所以我在VS中尝试过; 查询2运行,但返回未填充的用户属性。 查询3扩展方法似乎不存在,虽然它确实存在于Action本身而没有查询。

我想通了,谢谢你的建议。 解决方案是这样做(在我的问题中第二次尝试):

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

智能感知在查询后没有显示包含的原因是因为我需要使用以下内容:

 using System.Data.Entity; 

这一切都很顺利。

如果你想要的是一个查询,它将通过Action.UserId 外键属性返回其关联的User实体实际存在的所有Action实体,这将执行以下操作:

 var results = context.Actions .Include("User") .Where(action => context.Users.Any(user => user.UserId == action.UserId)); 

但是, 您不必使用外键属性进行过滤 ,因为您还具有导航属性 。 因此,您可以通过过滤Action.User导航属性来简化查询,就像在此示例中一样:

 var results = context.Actions .Include("User") .Where(action => action.User != null); 

如果您的模型声明Action.User属性永远不能为null(即, Action.UserId外键在数据库中不可为空),并且您想要的实际上是所有Action实体及其关联的Users ,则查询变得更简单

 var results = context.Actions.Include("User"); 

更好,重构友好的代码(EF6)

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

要么

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

更新3/31/2017

您还可以在lambda语法中使用include用于任一方法:

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

执行发布的问题中提到的基本查询,除非您返回匿名类型,否则您将无法看到用户属性,如下所示:

 from a in Actions join u in Users on a.UserId equals u.UserId select new { actionUserId = a.UserId . . . userProperty1 = u.UserId }; 

但是,要在ObjectContext上使用Include方法,您可以使用以下命令:

通过使用以下行确保您已关闭LazyLoading:

 entities.ContextOptions.LazyLoadingEnabled = false; 

然后继续

 var bar = entities.Actions.Include("User"); var foo = (from a in bar select a); 

我使用LoadWith选项

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

而已。 ctx是你的DataContext。 这对我有用:-)