NHibernate Polymorphic Request in Collection

I am trying to write a query in NHibernate. I don't care if I use the Criteria or HQL API, I just can't figure out how to write a query.

Here is my model:

public class LogEntry { public DateTime TimeCreated { get; set; } } public class Note : LogEntry { public string Content { get; set; } } public class Workflow { public IList<LogEntry> Log { get; set; } } 

I want the query to return all workflows containing a note with certain words in the contents of the note.

In pseudo-SQL, I would write this as:

 select w.* from Workflow w join w.Log l where l is class:Note where (Note)l.Content like '%keyword%' 
+4
source share
2 answers

I'm not sure about the criteria API, but HQL seems to do well with polymorphic queries even when looking for a property that exists only in a specific subclass. I expect the following to work:

 from Workflow w join w.Log l where l.class = Note and l.Content like '%keyword%' 
+3
source

I don't know if there is a better way, but for this I use subqueries:

 from Workflow w join w.Log l where l in ( select n from Note n where n.Content like '%keyword%' ) 

(if that doesn't work, write l.id in (select n.id... )

In criteria, you can directly filter properties that are available only in a subclass, but you shouldn't, because it only filters the first subtype that finds where this property is defined.

I also use subqueries:

 DetachedCriteria subquery = DetachedCriteria.For<Note>("n") .Add(Expression.Like("n.Content", "%keyword%")) .SetProjection(Projections.Property("n.id")); IList<Workflow> workflows = session.CreateCriteria<Workflow>("w") .CreateCriteria("w.Log", "l") .Add(Subqueries.PropertyIn("l.id", subquery)) .List<Workflow>(); 
+1
source

All Articles