NHibernate查询匹配所有标签

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

这是我的相关课程:

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查询匹配所有标签

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

发布评论

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

>www.elefans.com

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