NHibernate QueryOver投影多对一 [英] NHibernate QueryOver projection on many-to-one

查看:91
本文介绍了NHibernate QueryOver投影多对一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用many-to-one上的投影来使QueryOver工作.

I am trying to get a QueryOver working using a Projection on a many-to-one.

"Post"类具有属性many-to-one"Creator".

The class "Post" has a property many-to-one "Creator".

使用

session.QueryOver(Of Post).
Select(Projections.
Property(of Post)(Function(x) x.Creator).
WithAlias(Function() postAlias.Creator)).
TransformUsing(Transformers.AliasToBean(Of Post)()).
List()

可以,但是每个创建者都可以通过单个查询来检索,而不是像不使用选择/投影时那样使用联接来检索.因此,如果有5个帖子由5个不同的创建者创建,则将针对帖子列表运行1个查询,对创建者运行5个查询.

works BUT each creator is retrieved by a single query rather than using a join like it is done when not using a select/projection. So if there are 5 posts with 5 different creators, 6 queries will be run 1 for the list of posts and 5 for the creators.

我尝试使用JoinAlias使其正常工作,但实际上没有任何作用.

I tried to get it working using a JoinAlias but nothing really did the job.

我已经在寻找解决方案,但是我发现的所有解决方案都使用了Linq-Provider,因为实际的字段列表"是通过参数传递的,所以它并不适合.

I already searched for a solution, but all solutions I found did use the Linq-Provider which does not really fit since the actual "field list" is passed via a parameter.

除了linq提供程序之外,还有谁知道解决方案吗?

Does anyone know if there is a solution to this other than the linq provider?

推荐答案

有一个解决方案,我们可以将 projections 用于many-to-one,然后使用自定义结果转换器.

There is a solution, we can use projections for many-to-one and then custom result transformer.

免责声明:我可以阅读VB语法,但没有足够的勇气来编写...我希望您可以阅读C#并将其转换为VB....

所以我们可以这样投影:

So we can have projection like this:

// aliases
Post root = null;
Creator creator = null;

// projection list
var columns = Projections.ProjectionList();

// root properties
columns.Add(Projections.Property(() => root.ID).As("ID"));
columns.Add(Projections.Property(() => root.Text).As("Text"));

// reference properties
columns.Add(Projections.Property(() => creator.ID).As("Creator.ID"));
columns.Add(Projections.Property(() => creator.FirstName).As("Creator.FirstName"));

// so our projections now do have proper ALIAS
// alias which is related to domain model 
//  (because "Creator.FirstName" will be use in reflection)

var query = session.QueryOver<Post>(() => root)
    .JoinAlias(() => root.Creator, () => creator)
    .Select(columns)

现在,我们需要智能的 Transformer ,这是我们自己的习惯(可插入性是NHibernate的强大功能).在这里您可以找到一个:

Now we would need smart Transformer, our own custome one (plugability is power of NHibernate). Here you can find one:

我们可以像这样继续

var list = query
    .TransformUsing(new DeepTransformer<Post>())
    .List<Post>()

还请检查以下内容:

  • Fluent NHibernate - ProjectionList - ICriteria is returning null values
  • NHibernate AliasToBean transformer associations

这篇关于NHibernate QueryOver投影多对一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆