使用 NHibernate QueryOver 过滤和投影关联
假设您有一个与此类似的实体:
public class Mailinglist
{
public virtual Guid Id { get; set; }
public virtual ICollection<Subscriber> Subscribers { get; set; }
}
该实体的 NHibernate 映射正如您所期望的那样:Id
是标识符,Subscribers
使用
和
引用 Subscriber
实体。
现在,我有一个 Mailinglist
实例,并且需要获取与 Subscriber
属性上的某些过滤器匹配的前 100 个订阅者的列表。由于性能限制以及数据库中的数据量,myMailinglist.Subscribers.Where().Take()
不是一个选项。因此,我尝试组合一个 NHibernate 查询,该查询将从数据库中仅获取 100 个 Subscriber
实例。
我最初的尝试(没有任何过滤)是这样的:
var subscribers = session
.QueryOver<Mailinglist>()
.Where(m => m.Id == myMailinglistId)
.JoinQueryOver(m => m.Subscribers)
.Take(100)
.List();
这显然是不对的,因为我得到的列表包含 100 个对我已经熟悉的 Mailinglist
的引用。不过,生成的 SQL 看起来相当不错,让我认为我只需要显式添加投影/转换。
我一直在尝试寻找一些相关文档来帮助我,但似乎找不到任何解决此类查询的内容。有人可以提示我吗?
Suppose you have an entity similar to this:
public class Mailinglist
{
public virtual Guid Id { get; set; }
public virtual ICollection<Subscriber> Subscribers { get; set; }
}
The NHibernate mapping for the entity is as you would expect: Id
is the identifier and Subscribers
is mapped with <set>
and <many-to-many>
referincing a Subscriber
entity.
Now, I am in a situation where I have an instance of Mailinglist
and need to obtain a list of the first 100 subscribers matching some filter on Subscriber
properties. Due to performance constraints, and the amount of data in the database, myMailinglist.Subscribers.Where().Take()
is not an option. Hence, I am trying to put together a query for NHibernate which will fetch just the 100 Subscriber
instances from the database.
My initial attempt (without any filtering) goes like this:
var subscribers = session
.QueryOver<Mailinglist>()
.Where(m => m.Id == myMailinglistId)
.JoinQueryOver(m => m.Subscribers)
.Take(100)
.List();
This is obviously not right, as the list I get back contains 100 references to the Mailinglist
which I already new about. The generated SQL looks pretty good though, leaving me to think that I just need to explicitly add a projection/transformation.
I've been trying to find some relevant documentation to help me along, but cannot seem to find anything addressing this sort of querying. Can somebody hint me along?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
HQL不是更容易阅读吗?
尚未测试,但如下所示:
setMaxResults 应转换为 T-SQL“选择前 100 个...”
Would HQL not be easier to read?
Have not tested but something in the lines of:
The setMaxResults should translate to T-SQL "select top 100..."