使用SelectMany()的平面数据,如左连接

时间:2018-05-07 07:03:18

标签: c# entity-framework linq lambda

是否可以使用SelectMany()并使其行为类似于左连接?

我正在尝试将实体对象压缩为表格格式。只要有一个子对象,SelectMany()的工作方式就像一个魅力,但我希望看到所有的父对象,无论它是否有子节点。

public class Folder
{
    [Key]
    public int Folder_Id { get; set; }
    public string Folder_Name { get; set; }
    public int Folder_order { get; set; }
    public virtual ICollection<Module> Modules { get; set; }
}
public class Module
{        
    [Key]
    public int Module_Id { get; set; }
    public int? Folder_Id { get; set; }
    public string ModuleName { get; set; }
    public virtual Folder Folder { get; set; }

}
public static List<Menu> GetMenu()
{
    var Menu = db.Folder.Get();
    var q = from u in Menu
    from m in u.Modules
    select new {folderName = u.Folder_Name, moduleName = m.ModuleName};
    return q;
}

我需要的是:

FOLDERNAME =&#34; ENG&#34;,MODULENAME =&#34; REQ&#34;

FOLDERNAME =&#34; ENG&#34;,MODULENAME =&#34; BOM&#34;

FOLDERNAME =&#34;收件箱&#34;,MODULENAME =&#34;&#34;

FOLDERNAME =&#34;帮助&#34;,MODULENAME =&#34;&#34;

FOLDERNAME =&#34;信息中心&#34;,MODULENAME =&#34;&#34;

FOLDERNAME =&#34;采购&#34;,MODULENAME =&#34;缩进&#34;

1 个答案:

答案 0 :(得分:0)

当你在连接上选择导航属性时,你确实遵循了实体框架的推荐做法。唉,导航属性仅适用于内连接。因此,在这种情况下,SelectMany对您无济于事。所以你必须求助于加入:

var q =
    from u in Menu
    join m in Modules on u.Folder_Id equals m.Folder_Id into modules
    from mm in modules.DefaultIfEmpty()
    select new {folderName = u.Folder_Name, moduleName = mm?.ModuleName ?? String.Empty};
    return q;