开发者

Nhibernate criteria API for many-to-many

My object model is the following:

Item has many Tags and a Tag could belong to many Items

I'd like to execute the following query using criteria's.

SELECT * FROM Item item
WHERE item.Id in (Select it.ItemId from dbo.ItemToTags it where it.Tag_id = 'ONE')
AND item.Id in (Select it.ItemId from dbo.ItemToTags it where it.Tag_id = 'TWO')

Meaning I would like to give a collection of possible tags and then provide all items that have all of these tags:

I tried the following but I get not results :

CreateCriteria<Item>().CreateAlias("Tags", "Tags");
if (AndQuery) {
   foreach(var tag in Tags)
   {
      criteria.Add(Subqueries.PropertyEq("Tags.Id", DetachedCriteria.For<Tag>().A开发者_如何学编程dd(Restrictions.Eq("Id", tag))                                                   .SetProjection(Projections.Property("Id"))));
   }
} 


I'm not sure if your query could be translated as :

SELECT * FROM Item item 
join ItemToTags itt on itt.ItemId = item.Id
join Tags t on itt.TagId = t.Id
where t.Id in ('ONE','TWO')

If so, you should be able to do this :

CreateCriteria<Item>().CreateAlias('Tags','t')
   .Add(Restrictions.In('t.Id',new List<string>{'TWO','ONE'}).List<Item>();

That's assuming you have the tags collection mapped on the Item.

hth

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜