HasMany binds to key of wrong entity by default

James Cracknell's Avatar

James Cracknell

15 Jul, 2010 09:18 PM via web

Summary:

If you have an entity with two child entities in a references-relationship where only one of the relationships is bi-directional, then FluentNHibernate will (can?) choose the identity column of the wrong entity as the key column by default, creating a duplicate/invalid database column.

Details:

I have attached a simple console application which generates a configuration and exports the schema against the configured database as a Visual Studio 2010 project to illustrate the problem. The domain for the project consists of three entities, User, UserSetting and Import. Both UserSetting and Import reference User, however there is no inverse property allowing a User to retrieve associated Imports, as this is intended to be more for logging purposes. User has an IList<UserSetting> in a has-many relationship with UserSetting.

If you run the attached application, you can see that applying the fluent mappings to the configuration and then exporting the schema to a database results in the creation of an InitiatedBy_id column in the UserSetting table. If you look in the generated hbm file, you can see that the UserSetting collection in User is mapped with InitiatedBy_id as its key, despite the fact that the property does not belong to the UserSetting entity.

... 
<bag name="Settings" mutable="true">
    <key>
        <column name="InitiatedBy_id" />
    </key>
    <one-to-many class="FNHDuplicateFK.Domain.UserSetting, FNHDuplicateFK, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</bag>
...

Workaround:

My current workaround for this issue is to define the inverse property for the User - Import relationship and ignore it, however this is an extremely unintuitive issue as it doesn't make any sense to bind to a property that does not even belong to the referenced entity (Import::Id instead of UserSetting::Id). You could also manually specify the key column, but this is clearly still a bug.

  1. 2 Posted by James Cracknell on 15 Jul, 2010 09:24 PM

    James Cracknell's Avatar

    Another major aspect of the situation I neglected to mention, I am using trunk builds of both NHibernate and FluentNHibernate (687 & 5006 respectively,

  2. Support Staff 3 Posted by Paul Batum on 18 Jul, 2010 06:35 AM

    Paul Batum's Avatar
  3. Paul Batum closed this discussion on 18 Jul, 2010 06:35 AM.

Comments are currently closed for this discussion. You can start a new one.