【问题标题】:Linq to Entities query for hierarchyLinq to Entity 查询层次结构
【发布时间】:2020-09-28 18:34:32
【问题描述】:

我有这张桌子:

CREATE TABLE [md].[Services]
(
    [id] [nvarchar](36) NOT NULL,
    [Value] [nvarchar](500) NOT NULL,
    [Parentid] [nvarchar](36) NULL,
    [Status] [nvarchar](10) NOT NULL
)

我编写了一个查询来获得数据的扁平视图,如下所示:

SELECT
    bottomLevel.id as [Bot],
    midLevel.id as [Mid], 
    topLevel.id as [Top]
FROM
    md.Services bottomLevel
LEFT OUTER JOIN 
    md.Services midLevel ON bottomLevel.Parentid = midLevel.id
LEFT OUTER JOIN
    md.Services topLevel ON midLevel.Parentid = topLevel.id

但对于我的生活,我似乎无法用 EF 弄清楚这个的 LINQ 版本。

我想出了这个,但它返回更多的行,我还没有弄清楚我错过了什么......有什么想法吗?

var query = (from level3 in _db.Services
             from level2 in _db.Services
                               .Where(x => x.Parentid == level3.id).DefaultIfEmpty()
             from level1 in _db.Services
                               .Where(x => x.Parentid == level2.id).DefaultIfEmpty()
             select new
                    {
                        Bot = level3.id,
                        Mid = level2.id,
                        Top = level1.id,
                    });

【问题讨论】:

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


    【解决方案1】:

    我想通了。 我缺少一些东西,而且我正在倒退......

    var query2 = (
                    from level1 in db.ServiceTypes
                    join s1 in db.ServiceTypes on level1.ParentGuid equals s1.Guid into q1
                    from level2 in q1.DefaultIfEmpty()
                    join s2 in db.ServiceTypes on level2.ParentGuid equals s2.Guid into q2
                    from level3 in q2.DefaultIfEmpty()
                    select new
                    {
                        BottomGuid = level1.Guid,
                        MidGuid = level2.Guid,
                        TopGuid = level3.Guid,
                    }
    
                );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多