views:

199

answers:

1

Hi I have two c# classes one of which inherits from the other. Im trying to use NHibernate to map these classes such that I can query both as efficiently as possible. The base class is not abstract and needs to be able to be queried in its own right. The base class looks somthing like this.

public class Cat
{
    public int Id { get; set; }
    public string Name { get; set; }
}

the derived class looks something like this:

public class CustomerCat : Cat
{
    public int CustomerId { get; set; }
}

the derived simple extends the base and adds more properties to it. My Mapping file looks like this

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="Foo"
namespace="Foo">
<class name="Cat" table="Cat">
<id name="Id" column="CatId" type="Int32" unsaved-value="0">
<generator class="native" />
</id>
<property name="Name" column="CatName" type="string" />
<joined-subclass name="CustomerCat" table="CustomerCat">
<key column="CatId" />
<property name="CustomerId " column="CustomerId" />
</joined-subclass>
</class>
</hibernate-mapping>

The problem Im having is if I query for Cats via something like this:

IList<Cat> cats = session.CreateCriteria<Cat>().List<Cat>();

The sql generated will left join to by joined-subclass table. Can I query my base class without any refernce to any derived classes' tables in the query?

+1  A: 

I think in order to work in the way that you want it to (ie, not always do a left join) you have to create an abstract base class. The problem is that all CustomerCats are Cats and so it will have to join onto that table to get all the Cats (that is, Cats and CustomerCats).

If you do decide to create an abstract base class, see here for an overview of the different options and what SQL they result in.

Richard Bramley