How to write Criteria query when association <any> exists
I'm having trouble plotting the right criteria to fulfill a specific query - after a day of consulting with a Google professor, I'm hoping someone can point me in the right direction.
I have two objects of interest: OutputTsDef
andNamedAttribute
What I am trying to do is find all OutputTsDef
that have a specific meaning NamedAttribute
.
I can write separate criteria to find all NamedAttributes
that have a given name and value:
var attributesCriteria
= DetachedCriteria.For<INamedAttribute>()
.Add(Expression.Eq("Name", "some name"))
.Add(Expression.Eq("Value", "some value"));
How do I insert this into a query for OutputTsDef to constrain the results?
var criteria
= nHibernateSession.CreateCriteria(typeof(IOutputTsDefEntity));
// What do I write here?
var results = criteria.List();
NamedAttribute
looks like this: note the use [Any]
as we can
NamedAttributes
for many types of objects.
[AttributeIdentifier("DbKey", Name = "Id.Column", Value = "NamedAttributeID")]
[Class(Table = "NamedAttributes")]
public class NamedAttribute : BusinessEntity, INamedAttribute
{
[Any(0, Name = "Entity", MetaType = "System.String", IdType = "System.Int32")]
[MetaValue(1, Class = "Sample.OutputTsDef, Sample.Entities", Value = "OTD")]
[MetaValue(2, Class = "Sample.OutputTimeSeriesAttributesEntity, Sample.Entities", Value = "OTA")]
[Column(3, Name = "OwnerType")]
[Column(4, Name = "OwnerKey")]
public virtual IBusinessEntity Entity { get; set; }
[Property(Column = "Name")]
public virtual string Name { get; set; }
[Property(Column = "Value")]
public virtual string Value { get; set; }
... omitted ...
}
In regular SQL, I'll just add an extra "where" clause like this:
where OutputTsDefId
in ( select distinct OwnerKey
from NamedAttributes
where Name = ?
and Value = ?
and OwnerType = 'OTD' )
What am I missing?
(The question has also been posted to the NHUsers mailing list - I'll copy any useful information here.)
a source to share
This is what I ended up doing - embedding SQL subquery validation like this:
const string subquery
= "{alias}.OutputTsDefId in "
+"( select OwnerKey "
+ " from NamedAttributes na "
+ " where na.Name = ? and na.Value = ? and OwnerType='OTD')";
criteria.Add(
Expression.Sql(
subquery,
new object[] { attributeFilter.Name, attributeFilter.Value },
new IType[] { NHibernateUtil.String, NHibernateUtil.String }));
It's not ideal - I don't really like to work my way through NHibernate this way. But he does his job, which is very important.
I'm still curious about finding a clean NHibernate solution if there is one.
a source to share