1

I have an ICriteria that returns properties from a superclass Animal. Now I want to include in the results several properties from a subclass, Bird. For other subclasses, these properties should return null. I am using table-per-subclass inheritance. Is there any way to do this without adding lots of DetachedCriteria? NHibernate already left joins on the subclass tables; is there a way to project values from those joins?

Update: I need to be able to sort and filter on the subclass properties, and the entire query needs to support paging.

Here is my model:

public abstract class Animal
{
    public long Id { get; set; }
    public string Name { get; set; }
}

public class Cat : Animal
{
    public int WhiskerCount { get; set; }
}

public class Bird : Animal
{
    public long WingSpan { get; set; }
}

Given the following tables:

Animal:
 Id | Name      
----+--------------
 1  | Sylvester
 2  | Tweety
 3  | Maru
 4  | Big Bird

Cat:
 Id | WhiskerCount
----+--------------
 1  | 6
 3  | 12

Bird:
 Id | Wingspan     
----+--------------
 2  | 0.5
 4  | 10

I want the following result set:

 Id | Name       | Wingspan
----+------------+-------------
 1  | Sylvester  | <null>
 2  | Tweety     | 0.5
 3  | Maru       | <null>
 4  | Big Bird   | 10
Annabelle
  • 10,596
  • 5
  • 27
  • 26

1 Answers1

0
var results = session.CreateCriteria<Animal>()
    .List<Animal>()
    .Select(a => new 
    {
        Id = a.Id,
        Name = a.Name,
        Wingspan = (a is Bird) ? ((Bird)a).Wingspan : (int)null
    });
Firo
  • 30,626
  • 4
  • 55
  • 94
  • I forgot to mention in the question, but I need to be able to sort and filter on the Wingspan property and page the results. – Annabelle Nov 10 '11 at 19:21
  • then there is no easy way i think. you can use `DetachedCriteria` or `Expression.Sql("NHgeneratedAlias.Wingspan <> 10")` and `Order.Asc(Projections.SqlProjection("NHgeneratedAlias.Wingspan"));` – Firo Nov 11 '11 at 08:51