【问题标题】:Why does EF lose include data when performing a "from" join为什么执行“从”连接时 EF 会丢失包含数据
【发布时间】:2012-06-30 00:09:41
【问题描述】:

如果我有这样的 LINQ 表达式来提取用户表和相关数据。此查询按预期为我提供了一个填充的对象图:

    var query = from u in Context.Users
                    .Include("EventRegistrations")
                    .Include("State")
                select u;

但是,如果我将另一个相关的导航属性添加为“来自”,即使我不对其进行任何操作,我也只会在结果中获得单个对象数据,而没有包含数据。

    var query = from u in Context.Users
                    .Include("EventRegistrations")
                    .Include("State")
                from ur in u.UserRoles
                select u;

为什么会这样?我想在上面的表达式中的 where 子句中使用“ur”,但它消除了我获取包含的表数据的能力。

【问题讨论】:

  • 作为一个兴趣点,您还可以使用 lambda 包含语法,因此它在编译时是安全的,即 .include(u=>u.State) 您还需要一个 using System.Data.Entity; 语句
  • 为什么要加from ur in u.UserRoles?你不需要它在 where 子句中使用UserRoles
  • stackoverflow.com/questions/416847/…。我同意@LukLed。我建议显示您要执行的完整查询,可能有不需要第二个from 的替代解决方案。

标签: c# linq entity-framework linq-to-entities


【解决方案1】:

可能是因为你没有包含 UserRoles

var query = from u in Context.Users
                .Include("EventRegistrations")
                .Include("State")
                .Include("UserRoles")
            from ur in u.UserRoles
            select u;

【讨论】:

  • 我怀疑这是否能解决问题。为什么为 UserRoles 添加 Include 会突然导致 EventRegistrations 和 State 被加载?
猜你喜欢
  • 1970-01-01
  • 2015-05-14
  • 2013-10-17
  • 2014-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-17
  • 1970-01-01
相关资源
最近更新 更多