简体   繁体   中英

Hierarchical structure in repository pattern using EF or NHibernate

Please suggest approach/tutorial about how hierarchical structures are managed using repository pattern with EF4 (Code First) or nHibernate?

As an example, let say I've to display following:

Topic
 -> Comment1
   -> Comment1_1
   -> Comment1_2
      -> Comment1_2_1

What is ideal class structure and how should it wire up with ORM and repository pattern? There are lot of articles on repository pattern and EF/nHibernate but I couldn't find one using them with hierarchical structure.

My thoughts on class structure:

Class Topic 
   {
   public int ID {get;set;}
   public string Topic {get;set;}
   }

Class Comment
   {
   Public int ID {get;set;}
   Public int TopicID {get;set}
   Public string Comment {get;set;}
   Public int ParentID {get;set;}   //recursion will happen here
   Public int Level {get;set;} //Can be used to bypass recursion and display topic with all comments with indention based on Level
   }

Probably you're trying to map a tree to relational model. Take a look at how to map a tree in nhibernate .

If every comment gets reference to parent topic you don't need to do anything more. You will always load topic with all related comments and traverse hierarchy in your application logic because comment will have correctly configured parent (in this case it should also have collection of dependents to make traversal more easier).

So the algorithm for working with this structure should be:

  1. Load Topic and all related comments (every comment has TopicId despite of its position in hierarchy) - all EF stuff ends here because you have all data you need
  2. Process all comments where ParentId is null
  3. For each processed comment do everything you need
  4. For each dependent comment of currently processed comment go to 3. (recursion)

The more complex situation is if you want to work with some comments separately - for example get hierarchy of comments for some specified comment. In such case you must use native SQL to load comments and take advantage CTE (common table expression - only SQL Server 2005 and newer) for hierarchical queries. The approach was described in article posted by @pborovik and it is very similar in case of EF.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM