How to query NHibernate for specific type?
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.IndexOutOfRang开发者_Go百科eException : Invalid index 7 for this SqlParameterCollection with Count=7."
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.
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.
精彩评论