sympatric greg
sympatric greg

Reputation: 3179

Add a unique constraint on multiple columns with FluentNHibernate

I have a class that has a Primary Key as well as 2 foreign keys. Foreign combinations must be unique. I do not see a way to do this (at least since SetAttribute was deprecated).

James touched on this with SetAttribute: How to create a Multi-Column Index or Unique Constraint with NHibernate

Upvotes: 11

Views: 7355

Answers (1)

sympatric greg
sympatric greg

Reputation: 3179

This might be useful to someone else, FNH mapping of unique constraint is accomplished like this:

mapping.References<FirstClass>(x => x.FirstClass).UniqueKey("unique123"); mapping.References<SecondClass>(x => x.SecondClass).UniqueKey("unique123");

Further, it is explained that this only builds the constraint in the db, but that the developer is responsible to intercept duplicate insert attempts, otherwise an SqlException will be thrown saying an UNIQUE KEY constraint was violated.

from the FNH group

Upvotes: 22

Related Questions