I have the following Entity Framework
class with a column which is a Foreign Key
to the Primary Key
in the same table:
[Table("Items")]
public class Item
{
[Key]
public long ItemID { get; set; }
public string ItemName { get; set; }
public long? ItemParentID { get; set; }
[ForeignKey("ItemParentID")]
public virtual Item Parent { get; set; }
public virtual ICollection<Item> Children { get; set; }
}
The mapping above works great and I am able to get all the children items in the Children
property to the nth level simply by passing the ItemParentID
and selecting the Items
.
Now I have to bind this data along with all the children items and their children items etc. in my razor
view. I have started with the following code:
@if (Model.ChildItems.Count > 0)
{
foreach (Item parentItem in Model.ChildItems)
{
<div class="list-title">
<span>@parentItem.ItemName</span>
<ul>
@if (parentItem.Children.Count > 0)
{
foreach (Item childItem in parentItem.Children)
{
<li>
<a href="@FrontEndDomain.GetWebsiteURL()/@childItem.ItemID/details/@FrontEndDomain.GetURLString(Model.ParentItemName)/@FrontEndDomain.GetURLString(childItem.ItemName)" title="@childItem.ItemName">
@childItem.ItemName
</a>
</li>
}
}
else
{
<li>
No items available for @parentItem.ItemName.
</li>
}
</ul>
</div>
}
}
else
{
<h4>No items available.</h4>
}
The above code works well with 2 levels of children items but I want to bind data of all the child items and their child items to nth level. I have checked other questions on SO
but they are complex and most of them doesn't deal with lists
like Children
property mentioned above. Any simple way to get this done?