2

I'm using Fluent NHibernate with DiscriminateSubClassesOnColumn() to support subclassing. The column used to discriminate between subclasses is not mapped to an actual property on the entity.

How do I create a query which returns only entities of a given type?

Here's my try, where propertyName is the name of my discriminating column and value is the type name:

return _db.CreateCriteria<T>()
            .Add(Restrictions.Eq(propertyName, value))
            .List<T>();

However this gives me the error "could not resolve property: Type of: [my entity type]", which is because the entity itself doesn't have the property. If I add the property to my entity and map it I get another error: "System.IndexOutOfRangeException : Invalid index 7 for this SqlParameterCollection with Count=7."

hakksor
  • 1,380
  • 1
  • 9
  • 14

2 Answers2

3

You pass the type to the generic parameter T. For example, if Cat and Dog extend abstract class Animal:

return _db.CreateCriteria<Cat>()
        .List<Cat>();

returns all Cats

    return _db.CreateCriteria<Animal>()
        .List<Animal>();

returns Cats and Dogs.

Jamie Ide
  • 48,427
  • 16
  • 81
  • 117
0

You should just create a criteria based on the subclass you are interested in. For example if your entity hierarchy contains EntityB derived from EntityA, and you just want EntityB just do:

session.CreateCriteria<EntityB>().List();

and you will get all the entities of type entity B. No reason on working on the discriminator explicitly.

Felice Pollano
  • 32,832
  • 9
  • 75
  • 115