NHibernate query for matching all tags

 ̄綄美尐妖づ 提交于 2019-12-01 10:35:00

问题


Here are my relevant classes:

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; }
}

These are mapped with a many to many association. The intermediate table is named ItemsToTags.

Here's the question:

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?

This is the function signature:

IList<Item> GetItemsWithTags(IList<string> tagNames);

I need something like:

from Item item
where !tagsNames.Except(
    from item.Tags select item.Tags.Name
).Any()
select item

Thanks in advance for any help.


回答1:


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();

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.



来源:https://stackoverflow.com/questions/948978/nhibernate-query-for-matching-all-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!