我在Entity Framework 6中使用自引用模型,我需要根据用户的选择选择实例。 对于较大的选择,我得到一个例外:“SQL语句的某些部分嵌套太深。重写查询或将其分解为较小的查询。”
这是我的模型的简化版本:
public class Hierarchy
{
public int Id { get; set; }
public string Name { get; set; }
public int? ParentId { get; set; }
public virtual Hierarchy Parent { get; set; }
public virtual ICollection<Hierarchy> Children { get; set; }
}
用户的选择包含许多id。
我的数据库以
播种Id Name ParentId
1 Root NULL
2 parent-1 1
3 item-1-1 2
4 item-1-2 2
5 parent-2 1
6 item-2-1 2
7 item-2-2 2
8 child-1-1-1 3
9 child-1-1-2 3
10 child-1-2-1 4
11 child-1-2-2 4
12 child-2-1-1 3
13 child-2-1-2 3
14 child-2-2-1 4
15 child-2-2-2 4
我需要自己检索所选实例,以及所选实例的父项和子项。问题在于选择父母。这是一个Linq查询,它可以做到:
public static List<Hierarchy> Select(List<int> selection)
{
var result = context.Hierarchy
.Where(sub => sub.Children.Select(csub => csub.Id).Intersect(selection).Any());
}
不幸的是,它被转换为丑陋的SQL语句。致电时
var test = Hierarchy.Select(new List<int>() { 2, 6, 11 });
这会转换为:
SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Name] AS [Name],
[Extent1].[ParentId] AS [ParentId]
FROM [dbo].[Hierarchy] AS [Extent1]
WHERE EXISTS (SELECT
1 AS [C1]
FROM (SELECT
[Extent2].[Id] AS [Id]
FROM [dbo].[Hierarchy] AS [Extent2]
WHERE [Extent1].[Id] = [Extent2].[ParentId]
INTERSECT
SELECT
[UnionAll2].[C1] AS [C1]
FROM (SELECT
[UnionAll1].[C1] AS [C1]
FROM (SELECT
2 AS [C1]
FROM ( SELECT 1 AS X ) AS [SingleRowTable1]
UNION ALL
SELECT
6 AS [C1]
FROM ( SELECT 1 AS X ) AS [SingleRowTable2]) AS [UnionAll1]
UNION ALL
SELECT
11 AS [C1]
FROM ( SELECT 1 AS X ) AS [SingleRowTable3]) AS [UnionAll2]) AS [Intersect1]
)
为选择中的每个id添加UnionAll<n>
子查询级别。在实践中,用户可以选择许多id。如果有超过40个id,我会陷入漏洞抽象并获得异常。在任何情况下,它看起来都是次优查询。
基本上,我的查询需要查找所有具有任何所选项目的实例作为子项。这涉及为每个实例确定两个列表的交集:所选id的本地列表以及数据库中每个实例的子列表。
有人可以想办法使用Linq对实体执行此操作,而不会为每个选择项发出查询吗?
答案 0 :(得分:2)
可能是
public static List<Hierarchy> Select(List<int> selection)
{
var result = context.Hierarchy
.Where(sub => sub.Children.Any(csub => selection.Contains(csub.Id)));
}