Can NHibernate do this ...?

In my design, I need my entities to contain both a back reference and it’s id. I need the back references to do “while (parent != null)” type loops so I can build navigation bars. I need the parentId also, so that I can write queries and updates more easily (changing a parentId and then saving that entity directly is a lot easier than removing it from it’s current parent, adding it to another, then updating the parents).

So here’s the question, can NHibernate be made to work like this?

To recap, can NHibernate…

  1. have both a back reference and it’s id in the same entity?
  2. be made to work when updating an entity directly?

I am actually currently re-evaluating why I need this. But since you asked, I have the following HtmlHelper extension method:

public static MvcHtmlString IndentText(this HtmlHelper helper, char mark, int repeat, string text)
string marks = new String(mark, repeat * 2);
string indented = string.Format("{0} {1}", marks, text).Trim();
return MvcHtmlString.Create(indented);

And it is used like this in the views:

<&#37;@ Control Language="C#" Inherits="ViewUserControl<ForumManagerModel>" %>
<td><%: Html.DisplayFor(x => x.Id) %></td>
<td><%: Html.DisplayFor(x => x.Sequence) %></td>
<td><%: Html.IndentText('-', Model.IndentLevel, Model.Title) %></td>
<%: Html.ActionLink("Detail", "Detail", new { id = Model.Id }) %>
<%: Html.ActionLink("Edit", "Edit", new { id = Model.Id }) %>
<%: Html.ActionLink("Delete", "Delete", new { id = Model.Id }) %>

The model is built like this:

models.Add(new ForumManagerModel
Id = entity.Id,
Sequence = entity.Sequence,
Title = entity.Title,
IndentLevel = entity.IndentLevel 

And finally, the method in the entity that generates IndentLevel:

public int IndentLevel
int indentLevel = 0;
Forum parent = Parent;
while (parent != null)
parent = parent.Parent;
return indentLevel;

As I said, I’m looking for a better way to do this, but for now, I see no other way. Feel free to suggest something.

Calculating the indent level should work but is really going to hit your database / cache quite a bit, you’re probably going to be a lot better off by creating a field that stores the indent level and reserve the calculation when you need to re-calculate it when you change the hierarchy.

My first question would be why do you need this?

Sounds like code smell to me…:injured: