Question

I using the table per subclass strategy for inheritance in my application, as described in Ayende's post here.

However, when I am querying for a subclass specifically, say Company, and filtering on the Id (which I know), the resulting SQL is incorrect and gives me an error in SQL Server. The criteria:

session.CreateCriteria<Company>()
   .Add(Expression.Eq("Id", 25)
   .List<Company>();

The resulting generated SQL:

SELECT this_.PartyId,
       this_.CompanyName
FROM   Companies this_
       inner join Parties this_1_
          on this_PartyId = this_1_.Id
WHERE this_1_.PartyId = 25

The problem (last line - PartyId is not defined on the Parties table) is that the key column in the child table is used in the parent table. Since the "Id" derives from the Party class in C#, it kinda makes sense. But why does it use the key column "PartyId" instead of the Id "Id" defined in the Party mapping? And how can I make it work?

Thanks!

Edit: As asked, here are the mappings (same as the ones in the blog post)

<class name="Party"
    abstract="true"
    table="Parties">
<id name="Id">
    <generator class="identity"/>
</id>

<joined-subclass
    table="People"
    name="Person">
    <key column="PartyId"/>
    <property name="FirstName"/>
</joined-subclass>

<joined-subclass
    table="Companies"
    name="Company">
    <key column="PartyId"/>
    <property name="CompanyName"/>
</joined-subclass>

Was it helpful?

Solution

I finally found the problem. I had made a mistake in the mappings (I was using Fluent NHibernate to give me the mappings you see above) and I mapped twice the Id in the Party class :

public class PartyMap : ClassMap<Party>
{
    public PartyMap()
    {
        Table("Parties");
        Id(p => p.Id).GeneratedBy.Assigned();
        Map(p => p.Id);
    }
}

Since "Id" was mapped (not as an Id), when adding a where clause to the Id of Company, NHibernate was confused and used the key column "PartyId" as the mapped column for "Id", quite confusing! Removing the second mapping for Id solved the problem.

Anyway, my mistake!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top