I have a simple many to many relationship set up between tasks and tags. A task may have many tags and a tag may be assigned to many tasks. I use three tables to manage this - Task, Tag, and TaskTag. So far so good.
I am trying to write a criteria query for the following example...
Find all tasks that are tagged with 'Apple' (id = 1718) AND 'Orange' (id = 1717)
I found the following example which I tried to follow.
NHibernate many-to-many criteria
// Create sample list of tag ids.
var tagIDs = new List<long>();
tagIDs.Add(1718);
tagIDs.Add(1717);
// Create criteria and detached criteria.
var criteria = Session.CreateCriteria<Task>();
var detachedCriteria = DetachedCriteria.For<Task>("t")
.SetProjection(Projections.GroupProperty(Projections.Id()))
.Add(Restrictions.Eq(Projections.Count(Projections.Id()), tagIDs.Count))
.Add(Restrictions.EqProperty("t.ID", "ID"))
.CreateCriteria("Tags")
.Add(Restrictions.In("id", tagIDs.ToArray<long>()));
criteria.Add(Subqueries.Exists(detachedCriteria));
This is the SQL it produces...
SELECT this_.ID as ID4_0_, [MORE COLS HERE]
FROM dbo.[Task] this_
WHERE exists (
SELECT this_0_.ID as y0_
FROM dbo.[Task] this_0_
inner join dbo.TaskTag tags3_ on this_0_.ID=tags3_.TaskID
inner join dbo.[Tag] tag1_ on tags3_.TagID=tag1_.ID
WHERE this_0_.ID = this_0_.ID
and tag1_.ID in (2, 1718) <------ 1
GROUP BY this_0_.ID
HAVING count(this_0_.ID) = 1717 <------ 2
)
For some reason I cannot clearly understand, the parameters are getting misplaced.
- Notice that it puts the count (2) in the "in" list incorrectly, and
- It then puts the second tag id where the count should go.
When I modify the SQL to put the parameters in the correct locations, it works.
I must have the criteria incorrect, but I cannot see it.
I appreciate any help. Thanks!