fluent-nhibernatenhibernate-mappingjoined-subclass

How do I specify the name of the PK in the subclass table when using SubClass in FluentNHibernate?


I am attempting a subclass mapping in Fluent NHibernate.

In the parent class mapping, I have to specify the ID column name to prevent FNH guessing incorrectly:

Id(x => x.Id).Column("UserId");

I also need to specify the ID (or foreign key if you like) field name in the subclass mapping, since FNH is guessing that incorrectly too. How do I do that?


Solution

  • I haven't found a way to directly modify the mapping file itself, but I have found that overriding Fluent NHibernate's foreign key convention did the trick:

    public class FKConvention : ForeignKeyConvention
    {
      protected override string GetKeyName(FluentNHibernate.Member property, Type type)
      {
        if (property == null)
        {
          // Relationship is many-to-many, one-to-many or join.
          if (type == null)
            throw new ArgumentNullException("type");
          return type.Name + "Id";
        }
        // Relationship is many-to-one.
        return property.Name + "Id";
      }
    }
    

    The new convention has to be registered as explained at the bottom of this page: http://wiki.fluentnhibernate.org/Conventions.