NHibernate:QueryOver<>帮助 [英] NHibernate: QueryOver<> help
问题描述
我刚开始使用NHibernate,但是在运行更复杂的查询时遇到了麻烦.
I'm just starting out with NHibernate and I'm having trouble with running more complex queries.
我有一些带有附加标签列表的实体.用户将提供两个标签列表,包括和排除.
I have entities with a list of tags attached. The user will provide two lists of tags, include and exclude.
我需要找到具有所有include标记的所有实体,并在排除列表中排除具有任何标记的所有实体.
I need to find all the entities that have all of the include tags, and exclude any entites that have any tag in the exclude list.
下面是我的第一项努力-这显然是错误的,因为它列出了所有具有任何包含标签而不是全部包含标签的Display对象!
Below is my first effort- which is clearly wrong as its listing all Display objects that have any of the include tags rather than all!
非常感谢任何帮助.
var includeTagIds = (from tag in regime.IncludeTags select tag.Id).ToList<int>();
var excludeTagIds = from tag in regime.ExcludeTags select tag.Id;
var displays = session.QueryOver<Display>()
.JoinQueryOver<DisplayTag>(display => display.Tags)
.WhereRestrictionOn(tag => tag.Id)
.IsIn(includeTagIds).List().Distinct();
return displays.ToList();
推荐答案
该查询并非易事(请考虑如何使用原始SQL进行此操作).我认为以下方法会起作用(需要两个相关的子查询):
That query isn't trivial (have a think about how you might do this using raw SQL). I think the following will work (requiring two correlated sub-queries):
Display displayAlias = null;
var countIncludedTagsSubquery =
QueryOver.Of<Display>()
.Where(d => d.Id == displayAlias.Id)
.JoinQueryOver<DisplayTag>(d => d.Tags)
.WhereRestrictionOn(t => t.Id).IsInG(includedTagIds)
.Select(Projections.RowCount());
var excludedTagsSubquery =
QueryOver.Of<Display>()
.Where(d => d.Id == displayAlias.Id)
.JoinQueryOver<DisplayTag>(d => d.Tags)
.WhereRestrictionOn(t => t.Id).IsInG(excludedTagIds)
.Select(t => t.Id);
var displays =
session.QueryOver<Display>(() => displayAlias)
.WithSubquery.WhereValue(includedTagIds.Count).Eq(countIncludedTagsSubquery)
.WithSubquery.WhereNotExists(excludedTagsSubquery)
.List();
这篇关于NHibernate:QueryOver<>帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!