tags:

views:

270

answers:

3

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

+1  A: 

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.

Mark Rogers
A: 

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

Surya
see my updated answer above
Surya
A: 

@m4bwav - thanks. I tried the unique property, but it didn't seem to change anything. I can still call Session.Save with a new entity containing the same name as an existing one, and a new row is added to the table. I also tried setting the unique constraint on the column in the database, but then we just hit a sql exception when nHibernate tries to insert the row.

@Surya - thanks. This is actually what I've tried, but then I can't modify the entity that was passed into Add. Somehow nHibernate can modify it - I haven't figured out what I'm missing there.

Ideally, what I'm looking for is for session.Save() to auto-generate the SQL to select for an existing record, and if found, just populate the passed-in entity / otherwise, insert a new row.