NHibernate查询匹配所有标签 [英] NHibernate query for matching all tags
问题描述
这是我的相关课程:
public class Item {
public virtual int Id { get; protected set; }
public virtual IList<Tag> Tags { get; set; }
}
public class Tags {
public virtual int Id { get; protected set; }
public virtual string Name { get; set; }
public virtual IList<Item> Items { get; set; }
}
这些被映射为多对多关联.中间表名为ItemsToTags.
These are mapped with a many to many association. The intermediate table is named ItemsToTags.
这是问题:
给出一个字符串列表,如何创建一个NHibernate查询,该查询返回所有具有所有
Tag
且所有Tag
与给定列表中的所有字符串匹配的Item
的Item
?
Given a list of strings, how do I create an NHibernate query that returns all
Item
s that have all theTag
s withName
s matching all the strings in the given list?
这是函数签名:
IList<Item> GetItemsWithTags(IList<string> tagNames);
我需要类似的东西:
from Item item
where !tagsNames.Except(
from item.Tags select item.Tags.Name
).Any()
select item
在此先感谢您的帮助.
推荐答案
您绝对可以使用HQL来做到这一点;我已经成功测试了.
You can definitely do this with HQL; I've successfully tested it.
var items = session.CreateQuery("SELECT i.Id FROM Item i JOIN i.Tags tags WHERE tags.Name IN(:tags) GROUP BY i HAVING COUNT(DISTINCT tags) = :tagCount")
.SetParameterList("tags", tagNames)
.SetInt32("tagCount", tagNames.Count)
.List();
这将为您提供Item
ID的列表,可用于获取Item
.但是GROUP BY
和HAVING
组合 在某些DBMS上可能效率不高.还有另一种使用迭代联接的查询方法,在某些DBMS上 可能更有效,但我无法使其正常工作(使用Criteria可能根本无法实现).如果可以,我将更新答案.
That will get you a list of Item
IDs which you can use to get the Item
s. The GROUP BY
and HAVING
combination may be inefficient on some DBMS though. There is another query method using iterative joins that may be more efficient on certain DBMS but I can't get it to work (may not be possible at all with Criteria). If I ever do, I'll update my answer.
这篇关于NHibernate查询匹配所有标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!