Chris Conway
Chris Conway

Reputation: 16519

How can I use a composite-id with a class as the id field in fluent nhibernate?

I've got a mapping file like this:

<class name="Resource" table="resource" discriminator-value="null">
    <composite-id name="Key" class="Models.Bases.ClientKey, Models">
        <key-property name="Id" column="ID" type="int"/>
        <key-property name="SiteId" column="clientID" type="int"/>
    </composite-id>
    <property name="Name" type="String">
        <column name="`name`" length="500" sql-type="varchar" not-null="false"/>
    </property>
</class>

which works just fine and here's the id class:

public class ClientKey
{
    public int Id { get; set; }
    public int ClientId { get; set; }
}

public class Resource
{
    public virtual ClientKey Key { get; set; }
    public virtual string Name { get; set; }
}

How can I remap this using FluentNhibernate? This code doesn't work:

WithTable("resource");
UseCompositeId()
   .WithKeyProperty(x => x.Key.Id, "ID")
   .WithKeyProperty(x => x.Key.ClientId, "clientID");
Map(x => x.Name);

It throws this error: Could not find a getter for property 'Id' in class 'Models.Resource'

Thanks!!!

Upvotes: 0

Views: 1252

Answers (1)

maciejkow
maciejkow

Reputation: 6453

I'm afraid you can't fix it without modifying Resource class. I have checked with Fluent NHibernate's source - here's what code that outputs composite-id part looks like:

XmlElement element = classElement.AddElement("composite-id");
foreach( var keyProp in keyProperties )
{
  keyProp.Write(element, visitor);
}

What is missing is "name" attribute, which should be set to "Key". Without this attibute, NHibernate fallbacks to default property name = "Id". As your class doesn't have Id property, NHibernate doesn't know what to do and throws an exception.

If you can't modify Resource class, you would have to use hbm mapping for this class or create a patch to fluent nhibernate (it is possible that this is known issue and someone's working on it - refer to fluent nhibernate's issue tracker).

Upvotes: 1

Related Questions