Click here to Skip to main content
12,625,201 members (37,798 online)
Click here to Skip to main content
Add your own
alternative version


21 bookmarked

NHibernate and Complex Types for Native Keys

, 3 Jun 2009 CPOL
Rate this:
Please Sign up or sign in to vote.
Learn how to use complex classes as primary (not composite!) keys with NHibernate

Primary keys may take several forms: guid, integer, long, etc. It often makes sense to represent the key field as a POCO rather than its native type.

Why would I do this?

First, it hides the implementation. I don't have to worry about whether the key is an integer or a long, instead, I interact with my complex type.

It allows me to do some more interesting things with a key, too. For example, let's say I did choose to use identity fields (integers) so one implementation of my key is a "CoreKey" that contains an "ID" of type Integer.

It is common to see people use 0 or -1 as a "null" or "uninitialized" value for this type of key. With my class, I can do a little more and define it like this:

/// <span class="code-SummaryComment"><summary>

Notice that when I create a key (CoreKey key = new CoreKey()), it is immediately initialized to CoreKey.Empty, a special value I can check for. Instead of "if id < 1", I can use "CoreKey.IsNullOrEmpty" and I can even TryParse this.

This is all and well until you try to wire the class into NHibernate. The classic example for an NHibernate mapping file goes something like this:

<?xml version="1.0" encoding="utf-8"?>
<nhibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="MyApp.Widget,MyApp" table="widgets">
    <id name="Id" column="WidgetId">
      <generator class="native"/>
    <property name="WidgetName" column="name" type="String" length="40"/>

That's all good and well, but our widget uses a CoreKey, right? So what now? Try to reference the type, and you start to have problems:

<id name="Id" column="WidgetId" type="Framework.CoreKey,MyApp"/>

Of course, this will blow up. Why? Because the type coming from the database is an integer, and our CoreKey is NOT an integer. So what do we do?

This seems like it should be a simple problem to solve, but I searched far and wide to find a solution. I was trying components and composite keys and everything in between. I finally found an example that mentioned using the special interface IUserType supplied by NHibernate to, well, create our own types.

Unfortunately, the example included referencing NHibernate, my "persistence engine" or data layer, and then applying the interface to my domain object ("business entity"). Can you imagine dirtying your entity layer with ugly references to the implementation of your data store? Shouldn't, couldn't, and wouldn't happen.

Fortunately, the solution was rather simple and straightforward. Thanks to C# and inheritance, my domain objects only have to know about a CoreKey. However, my data layer can interact with something smarter, something that implements the IUserType interface AND talks the language of CoreKey.

Introducing CoreKeyProxy, an object defined in the data layer of the application. Here is the meat ... I've edited out comments and some of the other methods, and included the key items that map the database values to the custom type:

public class CoreKeyProxy : CoreKey, IUserType
    public object NullSafeGet(System.Data.IDataReader rs, string[] names, object owner)
        object r = rs[names[0]];
        if (r == DBNull.Value)
            return null;
        return new CoreKey((int)r);  
    public void NullSafeSet(System.Data.IDbCommand cmd, object value, int index)
        IDataParameter parameter = (IDataParameter)cmd.Parameters[index];
        parameter.Value = value == null ? null : (object)((CoreKey)value).ID;  
    public Type ReturnedType
        get { return typeof(CoreKey); }
    public global::NHibernate.SqlTypes.SqlType[] SqlTypes
        get { return new[] { new SqlType(DbType.Int32) }; }

Now I simply define my id as type="CoreKeyProxy" and voila! I'm able to integrate it seamless with my key class.

Jeremy Likness


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Jeremy Likness
Architect iVision
United States United States
Jeremy Likness is a principal consultant and leads the application development practice at iVision, Inc. Jeremy, an experienced entrepreneur and technology executive, has successfully helped ship commercial enterprise software for 20 years. He specializes in catalyzing growth, developing ideas and creating value through delivering software in technical enterprises. His roles as business owner, technology executive and hands-on developer provided unique opportunities to directly impact the bottom line of multiple businesses by helping them grow and increase their organizational capacity while improving operational efficiency. He has worked with several initially small companies like Manhattan Associates and AirWatch before they grew large and experienced their transition from good to great while helping direct vision and strategy to embrace changing technology and markets. Jeremy is capable of quickly adapting to new paradigms and helps technology teams endure change by providing strong leadership, working with team members “in the trenches” and mentoring them in the soft skills that are key for engineers to bridge the gap between business and technology.

You may also be interested in...

Comments and Discussions

-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.161128.1 | Last Updated 3 Jun 2009
Article Copyright 2009 by Jeremy Likness
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid