Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 588
sympatric greg Avatar asked Nov 30 '10 15:11

sympatric greg


People also ask

Can you have multiple unique constraints on a single table?

However, you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table. The following SQL creates a UNIQUE constraint on the "ID" column when the "Persons" table is created: To name a UNIQUE constraint, and to define a UNIQUE constraint on multiple columns, use the following SQL syntax:

How many unique and primary key constraints can I have?

However, you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table. The following SQL creates a UNIQUE constraint on the "ID" column when the "Persons" table is created:

What happens when uniqu constraint is created in SQL Server?

After uniqu constraint is created, developers can not insert any record to the table containing duplicate key with existing table data. Let's make a sample case which violate unique constraint on SQL Server table and see what happens.

How do I create a unique constraint in access?

To create a unique constraint. On the Table Designer menu, click Indexes/Keys. In the Indexes/Keys dialog box, click Add. In the grid under General, click Type and choose Unique Key from the drop-down list box to the right of the property. On the File menu, click table name.


1 Answers

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

like image 198
sympatric greg Avatar answered Sep 21 '22 11:09

sympatric greg