Click here to Skip to main content
15,797,984 members
Please Sign up or sign in to vote.
0.00/5 (No votes)

Let's say I have table with menu items. Each item have id and id of it's parent. Standart. How can I select tree (list in list or smth else) using linq without string sql and post-processing (i.e. .ToList().AsHierarchy())? Is that possible?

1 solution

You should map a list of children to a menu item class. That way each instance of a menu item also contains its children and you can easily iterate them. All you have to do is to select menu items where ParentId=0.

[Bag(0, Name = "Children", Inverse = true, Lazy = CollectionLazy.False)]
[Key(1, Column = "MenuItemParentId")]
[OneToMany(2, ClassType = typeof(MenuItem))]
public virtual IList<menuitem> Children
    get { return _children; }
    set { _children = value; }

Or by xml mapping (must still have the Children property in the class, though):
<bag name="Children" lazy="false" inverse="true">
    <key column="MenuItemParentId" />
    <one-to-many class="Your.Namespace.MenuItemParentId, Your.Namespace" />
Share this answer
kornakar 23-May-11 8:01am    
Please ignore the tag at the end of the code block; it's somehow automatically added by pre tag...
Bruno Renato 20-Apr-12 10:49am    
Thanks for solution. This help me a lot.
Alex Cherkasov 28-Jan-14 11:16am    
Will it cause SQL N+1 issue?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900