Azure DevOps, Scrum, & .NET Software Leadership and Consulting Services

Free course! Predicting the Future, Estimating, and Running Your Projects with Flow Metrics

HOWTO: Create a UNIQUE constraint using NHibernate

I got an email question yesterday about how to create a UNIQUE contraint on a table using NHibernate.  After some research on the NHibernate Forum and digging through the NHibernate source code, I was able to find a solution.

(NOTE: my blog engine, .Text doesn’t unfornately allow me to put html or xml directly in the text of a post so I’m putting element names in quotes.)

Usually, when you’re mapping properties you only deal with the “property” element but “property” has an optional child element, “column” that lets you specify more detail for how NHibernate handles the column mapping.  One of the attributes is “unique-key” and it lets you define a named, unique grouping of properties/columns.  Set the unique-key attribute to the same value for all properties you want to group together and Voila! a UNIQUE constraint. 

Here’s a sample class mapping with a UNIQUE constraint on FirstName and LastName. 







One response to “HOWTO: Create a UNIQUE constraint using NHibernate”

  1. Freeman Avatar

    Thank you! 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.