我有以下方法使用
LinqTosql获取节点的所有父节点,但我不知道它对性能有多大影响.
来自NodeTable:
public partial class Node { public List<Node> GetAllParents(IEnumerable<Node> records) { if (this.ParentID == 0) { // Reach the parent,so create the instance of the collection and brake recursive. return new List<Node>(); } var parent = records.First(p => p.ID == ParentID); // create a collection from one item to concat it with the all parents. IEnumerable<Node> lst = new Node[] { parent }; lst = lst.Concat(parent.GetAllParents(records)); return lst.ToList(); } }
好吗 !!或任何改善它的想法!
谢谢.
解决方法
因此,上面的代码是向上(父)方向的父子层次结构.因此,在最坏的情况下,它将导致对数据库的n层次深度进行n次查询.我建议你稍微改变方法来尝试延迟执行
public IEnumerable<Node> GetAllParents(IEnumerable<Node> records) { if (this.ParentID == 0) { // Reach the parent,so create the instance of the collection and brake recursive. return new List<Node>(); } var parent = records.Where(p => p.ID == ParentID); var parents = parent.Concat(parent.GetAllParents(records)); return parent; }
我不是100%确定它是否可行但是想法是利用表达式树/延迟执行,以便在单个数据库之旅中触发多个查询.
另一个想法是编写一个存储的proc / view,它将返回所有父节点(在sql server中查看相同的CTE).
编辑:使用Where而不是First在上面的代码中查找parent,因为First肯定会立即进行评估 – (警告:仍然未经测试的代码)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。