NHibernate - string foreign key mapping

The legacy legacy database contains the following tables:

Teams ( TeamId INT PRIMARY KEY, Name VARCHAR(30) ) Players ( PlayerId INT PRIMARY KEY, Team VARCHAR(30) ) 

The foreign key in the players table refers to the name of the team, not to the team.

I tried to match the Team team to the players using the bag:

 <bag name="Players"> <key column="Team" foreign-key="Name" /> <one-to-many class="DataTransfer.Player, DataTransfer" /> </bag> 

But I get SqlException: Conversion error when converting varchar 'Arsenal' value to int data type

I was able to use the bag to map foreign keys in other areas, but in these cases the foreign key referred to the primary key of the parent table.

Edit: I am using NHibernate 2.0.1

+4
source share
4 answers

Now I'm not 100% sure if this works, but have you tried the one-to-one relationship?

Maybe something like this:

 <many-to-one name="Players" class="DataTransfer.Player, DataTransfer" column="Name" property-ref="Team" /> 

I believe this should work, according to the hacker NHibernate-ref - this is an attribute that is used to display stale data, where the foreign key refers to the unique key of the linked table, different from the primary key. This is similar to the situation you are in.

+3
source

I think there is a property-ref attribute to solve this problem.

 <bag name="Players"> <key column="Team" property-ref="Team" /> <one-to-many class="Player" property-ref="Team" /> </bag> 
+3
source

I believe that you will need to use the property-ref attribute to determine the field with which you will be associated. A foreign key attribute is used to create a DDL to create relationships (if you use this function).

0
source

Just found this: https://nhibernate.jira.com/browse/NH-1272 , it seems like this is a bug in NHibernate, and it is fixed in 2.1.0Alpha1.

I tried it in NHibernate 2.1.0Alpha2 and it works!

(the -ref property should only be in the map tag)

0
source

All Articles