在 Linq to entity 查询中包含不相关的 table

Include unrelated table in Linq to entity query

我有以下简化设置:

Public User
{

  //Primary key
  public int Id {get;set;}

  public string Name {get; set;}
}

Public UserInfo
{

  //Primary key
  public int Id {get;set;}

  //Foreign key to user table
  public int userKey {get; set;}
}

table之间的关系是一个用户到多个用户信息

我正在尝试 select 来自 user table 并包含 userInfo table.

我不能这样做:

var users = Context.user.Include(u => u.userInfos);

因为用户 table.

没有引用 UserInfo table

我能做到:

context.userInfo.include(x => x.user)

但是如果在 userInfo table 中没有相应的条目,这将不会 return 任何结果,这不是我想要的。此外,这将为每个 userInfo return 一行,而我想要用户一行,并将 userInfo 列表作为参数。

同样,我可以像这样加入 table:

var users = from us in Context.user
    join inf in Context.userInfo
    on us.Id equals inf.userKey
    select new //etc

但这也会 return 每个 userInfo 条目一行,与上述问题相同。

总而言之,是否有一种方法可以包含此 table 以产生与 include 函数相同的结果。

我知道我可以调整我的设置以包含这个,但这不是我在这里要问的。

我怀疑这不可能完成,但从我所有的谷歌搜索到目前为止,我还没有找到一个明确的答案....

I want one row for user, with a list of userInfo as a parameter

我假设您指的是 属性 的 userInfo 列表。我对您所问内容的理解是您正在寻找的内容:

var users = from us in Context.user
    join inf in Context.userInfo
        on us.Id equals inf.userKey into infg
    select new
    {
        User = us,
        UserInfos = infg
    };

join ... into相当于一个GroupJoin,即一个用户实体加入了一组用户信息。

更好的方法是使用导航 属性 user.userInfos(不情愿地遵循您的命名约定):

var users = Context.user.Include(u => u.userInfos);