Development With A Dot

Blog on development in general, and specifically on .NET



My Friends

My Links

Permanent Posts

Portuguese Communities

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.


mynkow said:

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.

# February 15, 2013 9:05 AM

Ricardo Peres said:


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.

# February 15, 2013 9:36 AM

NOtherDev said:

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.

# February 15, 2013 5:22 PM

Ricardo Peres said:


Sure there are valid use cases, otherwise there wouldn't be that option. But you will always have that additional SELECT and you have to figure a way to have multiple clients inserting records without overwriting each other. It's my opinion, just that. I think the benefits (by the way, what are they?) does not pay the additional trouble.

# February 16, 2013 2:05 AM

magellin said:

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

# February 18, 2013 12:26 PM

Ricardo Peres said:


Manually assigned id not guid.comb! :-)

With guid.comb, it is NHibernate who assigns the identifiers!

# February 18, 2013 1:32 PM