Попробовав несколько подходов, я решил использовать соединение, что-то вроде этого:
Как моя модель:
public class Branch
{
public int Id { get; set; }
public string Name { get; set; }
public int? ParentId { get; set; }
[NotMapped]
public string ParentName { get; set; }
}
Как мой контроллер:
public ActionResult Index()
{
var branches = db.Branches;
var query = from child in branches
join parent in branches on child.ParentId equals parent.Id into parentJoin
select new
{
Id = child.Id,
ParentId = child.ParentId,
Name = child.Name,
ParentName = parentJoin.FirstOrDefault().Name
};
var result = query.ToList().Select(e => new Branch
{
Id = e.Id,
ParentId = e.ParentId,
Name = e.Name,
ParentName = e.ParentName
}).ToList();
return View(result);
}
и как мой вид:
@model List<Rouyesh_Database.Models.Branch>
@foreach (var item in Model) {
if (item.ParentId == null)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.ParentName)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
@Html.ActionLink("Details", "Details", new { id=item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
</tr>
}
}