EmployeeId Name ManagerId
------------------------------
1 A null
2 B null
3 C 1
4 D 3
5 E 2
仅仅使用这个表,如何编写linq查询(使用linq to sql)递归获取父数据.
just using this table, how can a linq query (using linq to sql) be written to fetch the parent data recursively.
例如,如果选择的雇主 ID 为 4,则应提供 ID 为:4、3、1 的员工列表
For instance if the Employer Id selected is 4 it should give list of employees with Id: 4, 3, 1
谢谢.
这个 .AsHierarchy() 扩展方法可能有用:链接.但是,这只能通过提供一种简单的方法将结果放入链接对象中才能起作用.为了做到这一点,它只会获取所有记录并运行自己的本地递归查询.
This .AsHierarchy() extension method may be useful: link. However, this only works by providing an easy way to throw your results into linked objects. In order to do that, it'll just get all the records and run its own local recursive query.
如果您正在寻找可通过 LINQ to SQL 直接转换为递归 SQL 查询的 LINQ 查询,您将找不到它.为了获得最佳性能,存储过程中的 CTE 可能正是您所需要的.如果您有一个非常简单的页面,无论如何都需要加载整个树,那么 AsHierarchy 方法可能会满足您的需求.
If you're looking for a LINQ query that will directly translate to a recursive SQL query via LINQ to SQL, you won't find it. For the best performance, a CTE in a stored procedure is probably what you're looking for. If you have a really simple page that needs to load the whole tree anyway, the AsHierarchy method would probably fit your needs.
这篇关于linq to sql 递归查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!