Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can QueryOver be used to filter for a specific class?

I am currently dynamically constructing queries like so:

QueryOver<Base, Base> q = QueryOver.Of<Base>();

if (foo != null) q = q.Where(b => b.Foo == foo);
// ...

Now there are multiple mapped subclasses of Base (e. g. Derived) which I want to filter on, basically something like:

if (bar) q = q.Where(b => b is Derived); // does not work

or:

if (bar) q = q.Where(b => b.DiscriminatorColumn == 'derived'); // dito

How do I best achieve that, preferably - but not neccessarily - in a type-safe way? Can this be done using LINQ, too?

like image 246
Thomas Luzat Avatar asked Jan 12 '23 05:01

Thomas Luzat


2 Answers

This is not intuitive, but the following should work fine (QueryOver):

if (bar) q = q.Where(b => b.GetType() == typeof(Derived));

I'm not sure about a way to do this in LINQ-to-NH.

like image 149
Andrew Whitaker Avatar answered Jan 21 '23 11:01

Andrew Whitaker


The general QueryOver, asking for a subtype, would look like this:

Base alias = null;

var query = session.QueryOver<Base>(() => alias);

// this statement would be converted to check of the discriminator
query.Where(o => o is Derived);

var list = query.List<Derived>();

But this would result in a statement, expecting that discirminator is "MyNamespace.Derived". If this si not the case, we can use this approach:

Base alias = null;

var query = session.QueryOver<Base>(() => alias);

// here we can compare whatever value, we've used as discriminator
query.Where(Restrictions.Eq("alias.class", "Derived"));

var list = query.List<Derived>();

Here we are using the feature of NHibernate: ".class" which does return the value of discriminator

More details could be found here:

  • 17.1.4.1. Alias and property references
like image 40
Radim Köhler Avatar answered Jan 21 '23 11:01

Radim Köhler