0

我收到了这个查询

var pc = _session.Query<ValutaHistory>()
.Where(x => x.Valutum.ValutaBetegn == updateLine.ProductCurrency)
.Fetch(x => x.Valutum)
.OrderByDescending(x => x.ValutaHistoryID)
.First();

但这会导致以下 SQL:

select TOP (1) valutahist0_.ValutaHistoryID as ValutaHi1_187_0_,
           valutum1_.ValutaID           as ValutaID191_1_,
           valutahist0_.Kurs            as Kurs187_0_,
           valutahist0_.ts              as ts187_0_,
           valutahist0_.cts             as cts187_0_,
           valutahist0_.nts             as nts187_0_,
           valutahist0_.KjopKurs        as KjopKurs187_0_,
           valutahist0_.ValutaID        as ValutaID187_0_,
           valutum1_.ValutaBetegn       as ValutaBe2_191_1_,
           valutum1_.KursDato           as KursDato191_1_,
           valutum1_.Kurs               as Kurs191_1_,
           valutum1_.Enhet              as Enhet191_1_,
           valutum1_.Myntsort           as Myntsort191_1_,
           valutum1_.BrukesSalg         as BrukesSalg191_1_,
           valutum1_.Aktiv              as Aktiv191_1_,
           valutum1_.ts                 as ts191_1_,
           valutum1_.cts                as cts191_1_,
           valutum1_.nts                as nts191_1_,
           valutum1_.TallKode           as TallKode191_1_,
           valutum1_.Symbol             as Symbol191_1_,
           valutum1_.TallKode1          as TallKode14_191_1_,
           valutum1_.TallKode2          as TallKode15_191_1_,
           valutum1_.KjopKurs           as KjopKurs191_1_,
           valutum1_.CultureName        as Culture17_191_1_,
           valutum1_.TallKode3          as TallKode18_191_1_,
           valutum1_.ValutaTabellID     as ValutaT19_191_1_
from   ValutaHistory valutahist0_
       left outer join Valuta valutum1_
         on valutahist0_.ValutaID = valutum1_.ValutaID
order  by valutahist0_.ValutaHistoryID desc

显然 WHERE 子句只是缺少,这怎么可能?

4

2 回答 2

0

好吧,当您将条件放在左联接(您的 where 子句)的左侧时,您实际上会使左联接无效(对于相关表)。

即使左侧没有匹配项,左连接也可以从右侧返回记录。但是,当您将条件放在左表上时,您实际上有一个内部联接。

我不确定,但我怀疑 NHibernate 正在检测到这一点,并决定您的OrderBy()andFirst()子句优先于该Where()子句。

所以我会转过这个查询。查询并过滤父实体Valutum,然后获取子实体ValutaHistory并排序。

var pc = _session.Query<Valutum>()
                 .Where(x => x.ValutaBetegn == updateLine.ProductCurrency)
                 .FetchMany(x => x.ValutaHistory)
                 .OrderByDescending(x => x.ValutaHistoryID)
                 .First();
于 2013-06-03T19:50:15.417 回答
0

这有效

var pc = _session.Query<ValutaHistory>()
    .Where(x => x.Valutum.ValutaBetegn == updateLine.ProductCurrency)
    .OrderByDescending(x => x.ValutaHistoryID)
    .Fetch(x => x.Valutum)
    .First();
于 2013-06-04T10:11:34.030 回答