c# - Linq to SQL 嵌套对象

标签 c# .net linq performance linq-to-sql

我有一个名为 Category 的对象,它有一个 ID、名称和 OwnerId。然后我嵌套这些以创建子类别。如果类别具有所有者 ID,则它是子类别。子类别的数量没有限制,但每个项目只能有 1 个父项。很简单。

我的问题是,我需要在加载后访问子类别。如何使用 Linq 获取拥有类别。我知道所有者 ID,但我不知道所有者可能有多深。

基本上我正在寻找一种方法来获取 Id == X 的类别或子类别,但这可以存在于 6 级或更深的子类别中。

我试图避免每个子类别中每个子类别的循环....

最佳答案

还有另一种存储/检索树层次结构的方法,如 this fogbugz 中所述。博文:

Turns out there's a pretty cool solution for this problem explained by Joe Celko. Instead of attempting to maintain a bunch of parent/child relationships all over your database -- which would necessitate recursive SQL queries to find all the descendents of a node -- we mark each case with a "left" and "right" value calculated by traversing the tree depth-first and counting as we go. A node's "left" value is set whenever it is first seen during traversal, and the "right" value is set when walking back up the tree away from the node. A picture probably makes more sense:

enter image description here

The Nested Set SQL model lets us add case hierarchies without sacrificing performance.

How does this help? Now we just ask for all the cases with a "left" value between 2 and 9 to find all of the descendents of B in one fast, indexed query. Ancestors of G are found by asking for nodes with "left" less than 6 (G's own "left") and "right" greater than 6. Works in all databases. Greatly increases performance -- particularly when querying large hierarchies

Here's another post进入更多细节。它是使用 Sqlphp 编写的,但我认为您可以掌握它的要点并轻松地将 Linq 转换为 Sql。

关于c# - Linq to SQL 嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5301008/

相关文章:

.net - 运行 MSBuild 无法读取 SDKToolsPath

c# - 从 asp.net 读取配置文件

c# - 如何从通用 IDictionary 获取 IDictionaryEnumerator?

c# generic Delegate Error Cannot bind to the target method 因为它的签名

c# - 排名标识符无效

c# - 在 XAML 中使用在 Silverlight 代码中创建的静态对象

c# - Dapper 嵌套对象查询 - 不填充所有属性

c# - 无法进入或中断在 Linq 查询/表达式中调用的方法

c# - 我没有解决的类型的 Unity 注册错误

c# - 如何检查类 "is"是否是 C# 中作为变量给出的类型的实例?