The object-relational mapper for .NET

Composite with only a Many-To-One = Bad Idea

I can’t count with one hand, how many times I’ve seen this mapping in my few years of using nhibernate:

  <class name="Profile">
      <key-many-to-one name="User" column="UserId" class="User" />

    <!-- properties -->

The explanation that comes when you ask is almost always:

Well… It is the only way you can use a many-to-one as a primary key.

There are two things that you can see in that quote:

  • The developer found a workaround (and sometimes he is proud)
  • He wants a many to one!


First of all, it is not a many-to-one, because you CAN’T have many profiles for one user. It is not a many-to-one, so we need to find a better way to tell nhibernate what we want.

On the other hand, it is not a composite-id if you only have one thing.

This kind of relationship is named “one-to-one” because you have only one profile for only one user. As you can read in the reference documentation ( here ) :

There are two varieties of one-to-one association:

  • primary key associations

  • unique foreign key associations

If we want to have such schema (UserId as the PK) we are talking about the first one.

The mapping is as follow:

  <class name="UserProfile" >
    <id column="Id">
      <generator class="foreign">
        <param name="property">User</param>
    <one-to-one name="User"

And the class is pretty easy too:

public class UserProfile
    public int Id { get; set; }
    public User User { get; set; }
    //other properties

This tell nhibernate to use the id from User when inserting a Profile. There rest is like any other class.

If you want to get an UserProfile, without getting the user, you can execute: session.Get<UserProfile>(userId).

Posted Sat, 08 January 2011 01:54:35 AM by jfromainello
Filed under: mapping

comments powered by Disqus
© NHibernate Community 2016