Joe Future
Joe Future

Reputation:

How to tell nHibernate not to allow duplicate entries in a table?

I have a simple entity that has an Id (the primary key) and a string name. I'm looking for a way to tell nHibernate not to allow duplicate names in the table.

I'd like to have an Add method that can take a new entity (with Id = 0), and if necessary add the new entity & update Id. This works now. If the name already exists in the table, I want to simply update Id and return the existing Id.

I'd like to be able call it like this:

Foo foo = new Foo(name); // foo.Id = 0 FooRepository.Add(foo);

.. and afterwards foo.Id <> 0 and it was either added or an existing foo.name was found and its Id was returned.

thanks/jf

Upvotes: 0

Views: 977

Answers (2)

Surya
Surya

Reputation: 4972

I dont think nhibernate can match additionally on natural key . You would have to do that in the add method in the repository . i.e Look up by name ,if found update the name and save.( find by example might save you sometime here )

Looks like you want to use assigned id's instead of surrogate id here . May be map name as identifier and get rid of surrogate key

Upvotes: 0

Mark Rogers
Mark Rogers

Reputation: 97707

You have to set the unique attribute equal to true in the mapping file in order to make this a unique column.

<property name="serialNumber" unique="true" type="string" column="SERIAL_NUMBER"/>

If you intend for the column to be a primary key for that table, then put

<id name="CommentId">
    <column name="comment_id" not-null="false"/>
    <generator class="identity"/>
</id>

The column will automatically have a unique constraint on it.

Upvotes: 2

Related Questions