How to query NHibernate for specific type?

泄露秘密 提交于 2019-12-24 01:46:07

问题


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."


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/5119432/how-to-query-nhibernate-for-specific-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!