如何优化LINQ to SQL用于递归查询? [英] How to optimize LINQ-to-SQL for recursive queries?

查看:203
本文介绍了如何优化LINQ to SQL用于递归查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下SQL表:

 ObjectTable
--------------------------------------------------
|  ID      |  Name         |  Order  |  ParentID  |
|  int PK  |  nvarchar(50) |  int    |  int FK    |     

ObjectTable.ParentID 是一个可空的字段,与不同对象记录的ID的关系。 LINQ to SQL生成一个类,如下所示:

ObjectTable.ParentID is a nullable field with a relationship to a different Object record's ID. LINQ-to-SQL generates an class that looks like:

 public class DbObject{

      int ID { get; set; }

      string Name { get; set; }

      int Order { get; set; }

      int? ParentID { get; set; }

      DbObject Parent { get; set; }

      EntitySet<DbObject> ChildObjects { get; set; }

 }

当我加载一个 DbObject 实例,我需要能够递归地访问子对象,以便我可以将数据写入层次化的JSON对象。

When I load a DbObject instance, I need to be able to recursively access the child objects, so that I can write the data to a hierarchical JSON object.


  • 每次通过 DbObject.ChildObjects ?由于DB事务占用最长时间,因此加载递归层次结构似乎是一种非常低效的方式。

  • Will I execute a separate query everytime I access the elements via DbObject.ChildObjects? Since DB transactions take the longest, it seems like this is a very inefficient way to load a recursive hierarchy.

使用LINQ-to-SQL和/或EF执行递归查询的最佳做法是什么?

What is the best practice for executing a recursive query with LINQ-to-SQL and/or EF?

LINQ to SQL与普通表表达式
我发现 linq-to-sql中的通用表表达式(CTE)?

推荐答案

在我们的例子中,我们使用CTE创建了存储过程,并将它们放在l2s设计器上,并且像其他表一样工作,除了表现为一种方法而不是财产,我们迄今为止没有遇到任何问题。

in our case we have created stored procedures with CTE's and put them on the l2s designer and they work like any other Table except they behave as a method rather than property and we have experienced no problem with that so far.

这篇关于如何优化LINQ to SQL用于递归查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆