NHibernate many-to-one and unique violation of restrictions

I have a problem trying to model a many-to-one relationship in NHibernate, where the object on the one side has a unique constraint on the column. The problem is this:

I have two tables: "Person" and "Country". Each person has one and only one country associated with him. There can be many people in a country (really! :)), and the name of the Country is unique. The following is a display on the Face side:

<many-to-one Name="Country"> <column Name="CountryId"/> </many-to-one> 

On the side of the country:

 <property name="Name" unique="true"> <column name="Name" length="50"> </property> 

Now in the database, I have added a unique constraint on the Name column in the Country table. If I call Save () on an instance of Person, NHibernate will simply try to do INSERTS, while I expect it to check if the country name exists and use its identifier in the CountryID column in the Person table. Instead, an exception is thrown that occurs as a result of breaking a unique constraint in the database.

It seems to me that Nibernate should have enough display metadata to do the right thing (or does the unique property attribute not guarantee this?). Does anyone know how to do this or is there a workaround?

Thanks,

Martijn

+4
source share
2 answers

You need to assign a country instance to the Country property of the Person instance (and not just set the identifier). Sort of:

 Person p = new Person(); p.Country = session.Load<Country>(countryId); session.Save(p); 

Then NHibernate will know what to do. This also will not delete the database for the country, since the Load method will return the proxy server of the country and the only thing you refer to is the identifier of the country instance.

+6
source

I had a similar requirement and decided to use it with SaveOrUpdateCopy .

Suppose you have two different People objects, and each has a link to another Country object. As long as the country identifiers are the same, you will not get an exception, and there will be only one country in the database.

The only thing with this approach is that you will need to assign an identifier to the objects of your country before calling SaveOrUpdateCopy.

0
source

All Articles