这是我的相关课程:
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 Items that have all the Tags with Names 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 Items. 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查询匹配所有标签
发布评论