微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Linq to Entities查询层次结构

如何解决Linq to Entities查询层次结构

我有这张桌子:

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,});

解决方法

我知道了。 我遗漏了一些东西,我正在向后做...

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,}

            );

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。