gpt4 book ai didi

database - 如何在 NHibernate 中进行此投影?

转载 作者:搜寻专家 更新时间:2023-10-30 21:36:37 27 4
gpt4 key购买 nike

我的数据库中有这些实体

enter image description here

对于给定的Job,我想基本上得到以下形式的结果

<Translation>,<ExternalUnit.Text>,<ExternalTranslation.Text>

加入条件是 Translation.Unit.Text == ExternalUnit.Text

这是我目前所拥有的,工作正常:

var props = session.QueryOver<Translation>(() => translation)
.Select(c => translation.Id, c => externalUnit.Text, c => externalTranslation.Text)
.JoinAlias(() => translation.TranslationUnit, () => unit)
.JoinAlias(() => unit.Job, () => job)
.Where(() => unit.Job == job)
.JoinAlias(() => job.ExternalUnits, () => externalUnit)
.JoinAlias(() => externalUnit.ExternalTranslations, () => externalTranslation)
.Where(() => externalUnit.Text == unit.Text)
.List<object[]>();

var translations = session.QueryOver<Translation>(() => translation)
.JoinAlias(() => translation.TranslationUnit, () => unit)
.JoinAlias(() => unit.Job, () => job)
.Where(() => unit.Job == job)
.JoinAlias(() => job.ExternalUnits, () => externalUnit)
.JoinAlias(() => externalUnit.ExternalTranslations, () => externalTranslation)
.Where(() => externalUnit.Text == unit.Text)
.List<Translation>()
.ToList();

然后我遍历 translations,引用 props。但是,我不喜欢这种方法,因为我不必要地对数据库执行了两个(几乎相同的)查询,而不是一个。

但我无法获得所需的投影。我在想这样的事情:

var data = session.QueryOver<Translation>(() => translationAlias)                
.JoinAlias(() => translation.TranslationUnit, () => unit)
.JoinAlias(() => unit.Job, () => job)
.Where(() => unit.Job == job)
.JoinAlias(() => job.ExternalUnits, () => externalUnit)
.JoinAlias(() => externalUnit.ExternalTranslations, () => externalTranslation)
.Where(() => externalUnit.Text == unit.Text)
.Select(() => translation, () => externalUnit.Text, () => externalTranslation.Text)
.List()

但是,显然,NHibernate 不喜欢 Select(() => translation...) 位(它不允许我投影整个实体)。

理想情况下我想选择匿名类型,比如

var data = session.QueryOver<Translation>()
...
.Select(() => new { A = translation, B = externalTranslation })

但我想 NHibernate 目前还没有...

非常感谢您的任何建议。

最佳答案

我知道了! NHibernate 的 LINQ 提供者救了我。它的优点在于它可以选择匿名类型,这使得加入变得非常容易。以防万一有人好奇,这是针对我的特殊情况:

var q = 
(from c in
(from b in
(from translation in session.Query<Translation>()
join unit in units on translation.Unit equals unit
where unit.Job == job
select new { Translation = translation, Original = unit.Text })
join extUnit in externalUnits on job equals extUnit.Job
where extUnit.Text == b.Original
select new { Translation = b.Translation, ExternalUnit = extUnit })
join extTranslation in extTranslations on c.ExternalUnit equals extTranslation.Unit
select new { Translation = c.Translation, Suggestion = extTranslation })
.ToList();

它生成的SQL很合理,我很高兴:)

关于database - 如何在 NHibernate 中进行此投影?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6966671/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com