Kyle West
Kyle West

Reputation: 9108

How do I enforce a unique constraint on a HasManyToMany NHibernate relationship?

Assuming I have products and categories and every product can exist in more than one category how do I prevent ending up with something like this in my database? Do I have to code it into my domain layer or can NHibernate handle it?

What I Don't Want

Table: ProductsCategories

ProductId  CategoryId
---------  ----------
12         23
12         24
12         23
12         23

What I Do Want

Table: ProductsCategories

ProductId  CategoryId
---------  ----------
12         23
12         24

Upvotes: 1

Views: 185

Answers (1)

Jamie Ide
Jamie Ide

Reputation: 49261

You need to code it into your domain layer by overriding Equals on the objects and using set mapping for the collections. That will prevent the collections from containing duplicate items. You should also add a unique constraint to the database table. NHibernate can generate the unique constraint if you are using it for schema generation but I don;t have an example for you.

Upvotes: 2

Related Questions