Linq to Entities 查询层次结构
Linq to Entities query for hierarchy
我有这个table:
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 版本。
我想到了这个,但是它 returns 行多了,我还没有弄清楚我错过了什么......有什么想法吗?
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,
}
);
我有这个table:
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 版本。
我想到了这个,但是它 returns 行多了,我还没有弄清楚我错过了什么......有什么想法吗?
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,
}
);