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.
-Ben
Leave a Reply