I’ve been seeing a lot of commentary (from an NHibernate perspective) about using Guid as opposed to an int (and presumably auto-id in the database), with the conclusion that using auto-identity breaks the UoW pattern.
This post has a short description of the issue, but it doesn’t really tell me “why” it breaks the pattern (unless I’m misunderstanding which is likely the case.
Can someone enlighten me?
There are a few major reasons.
Using a
Guidgives you the ability to identify a single entity across many databases, including six relational databases with the same schema but different data, a document database, etc. This becomes important any time you have more than one single place where data goes – and that means your case too: you have a dev database and a prod database, right?Using a
Guidgives NHibernate the ability to batch more statements together, perform more database work at the very end of the unit of work / transaction, and reduce the total number of roundtrips to the database, increasing performance as well as conferring other benefits.Comment:
Random
Guids do not create poor indexes – natively, they create poor clustered indexes. There are two solutions.Use a partially sequential
Guid. With NHibernate, this means using theguid.combid generator rather than theguidid generator.guid.combis partially sequential for good performance, but retains a very high degree of randomness.Have your
Guidprimary key be anonclusteredindex, and put a clustered index on another auto-incrementing column. You may decide to map this column, in which case you lose the benefit of better batching and fewer roundtrips, but you regain all the benefits of short numbers that fit easily in a URL. Or you may decide not to map this column and have it remain completely within the database, in which case you gain better performance forGuids as primary keys as well as better performance for NHibernate doing fewer roundtrips.