树结构表和实体框架 [英] Tree stucture table and entity framework

查看:69
本文介绍了树结构表和实体框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有树状结构表,

  Table {Id,ParentId,Name} 

其中,Id是主键,父ID是外键,但在同一张表中。它将具有以下值:

  Id ParentId名称
1-N1

2 1 N2

3 1 N3

4 2 N4

这里,N2和N3是N1的子代,而N4是N2的子代



我正在使用Entity Framework和MVC来构建Web服务之类的其余部分。 b
$ b

如何使用实体框架递归获取所有子节点?

解决方案


如何使用实体框架递归获取所有子节点?


EF不支持递归查询。您可以轻松地映射@Eranga在注释中引用的结构,但是一旦加载实体,则必须手动定义急切加载(=必须说出深度),否则子实体将在第一次加载时通过延迟加载来加载



在EF中使用分层结构的最佳方法是使用数据库视图隐藏分层的SQL查询或直接使用SQL /存储过程


I have tree structure table like,

Table{Id, ParentId, Name}

where Id is primary key, and parent Id is a foreign key, but to the same table. It will have values like

Id            ParentId             Name
1              -                          N1

2              1                          N2

3              1                          N3

4              2                          N4

here, N2 and N3 is child of N1, and N4 a child of N2

I am using Entity framework and MVC to build rest like webservice.

How can I use entity framework to recursively to get all child nodes?

解决方案

How can I use entity framework to recursively to get all child nodes?

EF doesn't have support for recursive queries. You can map such structure easily as referenced by @Eranga in comment but once you load entities you must either manually define eager loading (= you must say how deep it should go) or your child entities will be loaded by lazy loading first time they are accessed (that is extremely inefficient).

The best way to work with hierarchical structures in EF is either using database view to hide hierarchical SQL query or using SQL / stored procedures directly.

这篇关于树结构表和实体框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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