NHibernate – Mapping a String Foreign Key

nhibernatenhibernate-mapping

The legacy database I've inherited 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 team name, rather than teamId.

I've attempted to map from Team to Players using a bag:

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

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

I've been able to use a bag to map string foreign keys in other areas, but in those cases the foreign key referred to the primary key of the parent table.

Edit: I'm using NHibernate 2.0.1

Best Answer

I think the property-ref attribute exists to solve this problem.

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