用于匹配所有标签的 NHibernate 查询

编程入门 行业动态 更新时间:2024-10-24 19:26:14
本文介绍了用于匹配所有标签的 NHibernate 查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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.

解决方案

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.

更多推荐

用于匹配所有标签的 NHibernate 查询

本文发布于:2023-10-26 23:17:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1531638.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:标签   NHibernate

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!