Derik Whittaker

Syndication

News


Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
Troubleshooting common mapping bugs with NHibernate

For all of its power and glory NHibernate is no different than any other tool which requires you to configure it before you can use it.  In the case of NHibernate you need to configure (map) each of the tables you want to access to the various entities in which they are going to populate.  And because you need to manually configure this, there is room for mistakes and errors. 

I wanted to outline some mapping errors I have run into while trying to learn NHibernate and explain how to resolve them.  We will be utilizing the FluentNhibernate mapping library to ease the process of creating our NHibernate mappings.

 

Common Issue #1 – Wrong/Invalid Table Name Used In Mapping

Issue: When the mapping from an entity to the table is not valid you will receive the below error.

Error: System.Data.SqlClient.SqlException: Invalid object name ‘YourNameHere’

Solution:

  1. Ensure that the entity name you are mapping is the same as the database table.
  2. Add WithTable( "TableNameHere" ); command to your mapping file.


Common Issue #2 – Missing primary key mapped for the table

Issue: when creating the mapping you fail to provide the primary key mapping for a table (Id() or UseCompositeId())

Error: System.Xml.Schema.XmlSchemaValidationException: The element 'class' in namespace…List of possible elements expected: 'meta, jcs-cache, cache, id, composite-id' in namespace'

Solution:

  1. Add a mapping for the primary key for your entity


Common Issue #3 – Wrong/Invalid Column Name Used In Mapping

Issue: When the mapping from an entity to the table is not valid you will receive the below error.

Error: System.Data.SqlClient.SqlException: Invalid column name 'YourColumnNameHere.

Solution:

  1. Check the mapping for your class/table and ensure that you have not provided the wrong database column name for your property


Common Issue #4 – Missing/Invalid property name mapping on Many-to-One, One-to-Many or Many-to-Many

Issue: When you setup your mapping to map to a backing field (_SomeField), but the name of the backing field you provide is not valid

Error: NHibernate.PropertyNotFoundException: Could not find field '_someField in class 'Full.Class.Name.Path.Here'

Solution:

  1. Check you entity to make sure you have the spelling of your backing field correctly.
  2. If you are using FluentNhibernate for your mapping make sure that your backing field name matches your property name, with the exception of the prefix (‘_’ or ‘m’).


Common Issue #5 – Could not find a Setter for a mapping

Issue: When you are trying to push data either into a backing field and you fail to provide the ‘access modifier’ or your property does not have a public ‘Setter’

Error: NHibernate.PropertyNotFoundException: Could not find a setter for property 'PropertyNameHere' in class 'Full.Class.Name.Path.Here’

Solution:

  1. If you are using a backing field, make sure you provide the access modifier. 
    .Access.AsCamelCaseField( Prefix.Underscore ) If using FluentNHibernate
  2. If you are not using a backing field, make sure your property has a public setter


Common Issue #6 – Fail to mark property or method as void for a class which is mapped

Issue: When creating your property or method on your class you forget to mark a class as virtual.

Error: NHibernate.InvalidProxyTypeException: The following types may not be used as proxies: ‘Some.Type.here’

Solution:

  1. Read the exception and mark the appropriate class as virtual.


Common Issue #7 – Invalid column foreign key mapping for a Many-To-One mapping

Issue: When trying to setup a mapping for a Many-to-One mapping the FK mapping is not setup correctly when the FK property name is different from the column name

Error: System.Data.SqlClient.SqlException: Invalid column name ‘SomeColumnName_id'

Solution:

  1. Ensure that you the spelling of your column name mapping correct.
  2. Add the syntax to manually map the FK column name using the .TheColumnNameIs("SomeColumnName`_ID") syntax (FluentNHibernate)

 

The 7 common issues I talked about above are in no way ALL the possible issues that you may come across, they are simply some that I have seen. I hope this helps someone else solve their problems.

Till next time,


Posted 02-21-2009 4:39 PM by Derik Whittaker

[Advertisement]

Comments

Mark Nijhof wrote re: Troubleshooting common mapping bugs with NHibernate
on 02-21-2009 7:50 PM

Very useful post! I found that some NHibernate errors were pretty descriptive, now I\ll first look at your post :)

DotNetShoutout wrote Troubleshooting common mapping bugs with NHibernate - Derik Whittaker
on 02-22-2009 3:34 PM

Thank you for submitting this cool story - Trackback from DotNetShoutout

Weekly Links #41 | GrantPalin.com wrote Weekly Links #41 | GrantPalin.com
on 02-23-2009 12:32 AM

Pingback from  Weekly Links #41 | GrantPalin.com

Reflective Perspective - Chris Alcock » The Morning Brew #292 wrote Reflective Perspective - Chris Alcock » The Morning Brew #292
on 02-23-2009 3:38 AM

Pingback from  Reflective Perspective - Chris Alcock  » The Morning Brew #292

DotNetKicks.com wrote Troubleshooting common mapping bugs with NHibernate
on 02-23-2009 9:04 AM

You've been kicked (a good thing) - Trackback from DotNetKicks.com

jdn wrote re: Troubleshooting common mapping bugs with NHibernate
on 02-24-2009 3:24 PM

Is Issue#6 failure to mark a class as void or virtual?

Derik Whittaker wrote re: Troubleshooting common mapping bugs with NHibernate
on 02-24-2009 3:28 PM

@jdn,

You are correct

jdn wrote re: Troubleshooting common mapping bugs with NHibernate
on 02-24-2009 3:42 PM

No, which is it?

Title: Common Issue #6 – Fail to mark property or method as VOID for a class which is mapped

Issue: When creating your property or method on your class you forget to mark a class as VIRTUAL.

So, is it failure to mark as VOID or failure to mark as VIRTUAL?

Derik Whittaker wrote re: Troubleshooting common mapping bugs with NHibernate
on 02-24-2009 3:49 PM

@jdn,

failure to mark it as virtual.

sushant khurana wrote re: Troubleshooting common mapping bugs with NHibernate
on 03-16-2009 3:28 AM

I already have done that.. I just wanted to know how it works.. as in.. If I expose the configuration from :

 private static ISessionFactory CreateSessionFactory()  

       {

            return Fluently.Configure()

               .Database(SQLiteConfiguration.Standard

                   .UsingFile(basefile))

               .Mappings(m =>                    m.FluentMappings.AddFromAssemblyOf<Program>())

               .ExposeConfiguration(BuildSchema)

               .BuildSessionFactory();

       }

and use it here :

private static void BuildSchema(NHibernate.Cfg.Configuration cfg)

       {

           config = cfg;          

       }

private static void update_the_schema()

    {

      new SchemaUpdate(config).Execute(true, true);        

    }    

//Here config is that static configuration variable obtained from ExposeConfiguration method...  

sushant khurana wrote re: Troubleshooting common mapping bugs with NHibernate
on 03-16-2009 3:28 AM

I already have done that.. I just wanted to know how it works.. as in.. If I expose the configuration from :

 private static ISessionFactory CreateSessionFactory()  

       {

            return Fluently.Configure()

               .Database(SQLiteConfiguration.Standard

                   .UsingFile(basefile))

               .Mappings(m =>                    m.FluentMappings.AddFromAssemblyOf<Program>())

               .ExposeConfiguration(BuildSchema)

               .BuildSessionFactory();

       }

and use it here :

private static void BuildSchema(NHibernate.Cfg.Configuration cfg)

       {

           config = cfg;          

       }

private static void update_the_schema()

    {

      new SchemaUpdate(config).Execute(true, true);        

    }    

//Here config is that static configuration variable obtained from ExposeConfiguration method...  

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)