0
votes

I have some class hierarchy, mapped by the code into several tables. One for base abstract class, and one table per concrete class. Classes hierarchy is relatively simple, like this:

public abstract class BaseClass {
  // some common fields here
}

public class Subclass1 : BaseClass {
}

public class Subclass2 : BaseClass {
}

public class Subclass3 : BaseClass {
}

The problem appears when I try to Query over BaseClass to retrieve a collection of all subclasses from the database.

var allInstances = dbSession.QueryOver<BaseClass>().List();

Error message is very simple: "Cannot instantiate abstract class or interface".

So my question is: is there a way to have one single query for my scenario, or I have to run one query per subclass?

2

2 Answers

0
votes

I am not sure about the QueryOver of Nhibernate, but you could do a polymorphic query using the Criteria.

var result = dbSession.CreateCriteria<BaseClass>()
                      .List<BaseClass>();

You also could try using the Linq

using NHibernate.Linq;

/// ...

var result = dbSession.Query<BaseClass>()
                      .List();
0
votes

Nhibernate supports the ability to fetch multiple objects of different types in a hierarchy in one query. This can be done using any of the supported querying (Queryover, HQL, ICriteria).

It would have been helpful to have your mapping, as it would let us know what the table structure is.

I had this issue recently, and found it was bad data. I had a single table for the abstract base class and 20+ tables for the subclasses (one per subclass). The base class table had a record which had no matching record in any of the subclass tables. I'm guessing that when this happens NHibernate decides that the object being fetched must be an instance of the base class (since it can't find a matching record in any sub class table), and tries to instantiate it resulting in the error "Cannot instantiate abstract class or interface".

Check your data.