I need to display some parent-child relation data in view.
Following is my code:
@model PagedList.IPagedList<Test.Domain.TestTable>
<table width="100%">
<tr>
<td>Name</td>
<td>Parent</td>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.ParentID)
</td>
</tr>
}
<tr>
<td>
Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount
-----------------
-----------------
</td>
</tr>
</table>
Now I want to display the parent name instead of parent id, which has following structure in database:
ID Name ParentID
1 John Null
2 Dean 1
3 Sam 1
To display parent name, I tried following code, but none of this works:
@Model.Where(screenParent => screenParent.ID == item.ParentID).Select(screenParent => new { screenParent.Name})
It displays
System.Linq.Enumerable+WhereSelectEnumerableIterator`2[Test.Domain.TestTable,<>f__AnonymousType5`1[System.String]]
Can you suggest why it display above line of code?
Also what can be done to achieve the parent name instead of parent id.
Thanks in advance.
Making a couple of assumptions here.
Do you have a property on your model for Parent instead or are you just pulling in ParentID? If you are pulling in just the ID i suggest changing your model/mapping so that you are pulling in the entire object reference by the FK.
If you are already pulling in the entire Parent object, know that entity framework won’t automatically lazy load your Parent for you. You have to explicitly tell it to load it when you query TestTable.
You can do this in 2 different ways.
Make your Parent property Virtual. i.e.
public virtual TestTable Parent { get; set; }
Then when you try and access TestTable.Parent it will load from the database. This will allow you to access the name.
Explicitly load Parent when you query test table i.e.
myDBContext.TestTables.Include(“YourParentPropertyName”).Where(….);
The end results in your view will look like this:
Let me know if that helps.