NHibernate Pitfalls: Manually Assigned Identifiers

This is part of a series of posts about NHibernate Pitfalls. See the entire collection here.

When you use manually assigned identifiers, you are responsible for assigning a valid id to your entity. By valid, I mean, some key that doesn’t already exist on the database.

Because it’s not NHibernate who is managing it, when time comes for the entity to be saved, NHibernate needs to issue a SELECT statement in order to find out if a row with the given id exists, in which case an UPDATE statement will be issued, otherwise, it will be an INSERT. So, you have to be very careful not no overwrite an existing row unintentionally.

Generally speaking, there’s no need to use manually assigned identifiers, and you should avoid them.



  • We use Manually Assigned Identifiers everywhere because the client needs the ID. If the IDs are automatic then u have to do extra query for displaying data. I recommend you delete the last sentence from the post.

    PS: keep the great work, I enjoy this series.

  • mynkow:
    Thanks! I also enjoy different opinions! ;-)
    I keep my opinion: identifiers should be managed by NHibernate. A different thing is natural ids - properties that have special meaning and need to be unique. NHibernate also supports this.

  • We're using assigned identifiers for externally-controlled dictionaries and we had no problem with that. We're preloading the dictionaries upfront so we're not affected by the additional select issue. Anyway, I think you shouldn't be so unequivocal about assigned identifiers, there are a valid use cases for them.

  • If you use GuidComb you don't have the extra select problem.

  • magellin:
    Manually assigned id not guid.comb! :-)
    With guid.comb, it is NHibernate who assigns the identifiers!

Comments have been disabled for this content.