Filtering NHibernate SubType with ICriterion
Is there any way I can filter my NHibernate query on the SubType field before开发者_运维问答 I hit the database by adding an ICriterion to my executing DetachedCriteria?
My code looks something like this:
DetachedCriteria detachedCriteria = DetachedCriteria.For(typeof(MyObject));
ProjectionList projectionList = Projections.ProjectionList();
projectionList.Add(Projections.SqlProjection("{alias}.SubType as SubType", new string[] { "SubType" }, new IType[] { TypeFactory.GetAnsiStringType(15) }));
dc.SetProjection(projectionList);
dc.Add(Expression.Eq("SubType", "MYOBJECT"));
using(ISession session = ...)
{
ICriteria criteria = detachedCriteria.GetExecutableCriteria(session);
// Blows up because I don't know how to reference the SubType
// field with an ICriterion (Expression.Eq("SubType", "MYOBJECT"))
IList list = criteria.List();
...
}
While this may not be the right way to accomplish my goal, I'm hoping it's at least possible because I'm not looking forward to having to refactor my interfaces that expect / produce an ICriterion. I also don't necessarily have access to the session anywhere near where I need to create the ICriterion object (but I have full control over the aliasing/naming of the various NHibernate fields/tables that will be used).
Took quite a bit of googling around to find the answer to this, here it is: http://derek-says.blogspot.com/2008/08/excluding-particular-derived-types-in.html
ICriteria crit = sess.CreateCriteria(typeof(Mammal));
crit.Add( Expression.Not( Expression.Eq("class", typeof(DomesticCat)) ) );
List mammals = crit.List();
精彩评论