One exception you may run across while using Fluent Nhibernate (or straight up NHibernate) is System.Data.SqlClient.SqlException: Invalid column name ‘……’. This is normally caused because you did not provide the correct column name when doing your mapping.
Lets take a look at the code below which is trying to map a many-to-one relationship to another entity.
References( x => x.BusinessUnit )
.Access.AsCamelCaseField( Prefix.Underscore )
.WithForeignKey( "DATASET_ID" )
.FetchType.Join
As you can see from the code we are trying to setup the mapping to our BusinessUnit entity, and we are providing the foreign key as ‘DataSet_ID’. However when we generate the .hbm.xml file and run the code it throws the Invalid Column name exception saying that it cannot find BusinesUnit_ID.
Here is the .hml.xml snippet for this mapping
<many-to-one access="field.camelcase-underscore" foreign-key="DATASET_ID" fetch="join" name="BusinessUnit" column="BusinessUnit_id" />
At first glance you may be wondering why it is trying to use BusinessUnit_ID as the column name. The reason is that FluentNHibernate assumes that the column u are mapping against in the patent is the ‘id’ value of the entity (BusinessUnit_ID). However, in my case this is not true. In order to resolve this I simply need to tell FluentNHiberhate what the true column name is. I can do so with the following code
References( x => x.BusinessUnit )
.Access.AsCamelCaseField( Prefix.Underscore )
.WithForeignKey( "DATASET_ID" )
.TheColumnNameIs( "DATASET_ID" )
.FetchType.Join
When I run this code, it will generate the following .hbm.xml file
<many-to-one access="field.camelcase-underscore" foreign-key="DATASET_ID" fetch="join" name="BusinessUnit" column="DataSet_ID" />
So, if you ever find you self with the Invalid column name exception make sure you have completely setup your mappings.
Till next time,
Posted
02-13-2009 2:51 AM
by
Derik Whittaker