Linq 2 NHibernate无视条件

时间:2013-06-03 14:44:41

标签: nhibernate linq-to-nhibernate

我收到了这个查询

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子句,这怎么可能?

2 个答案:

答案 0 :(得分:0)

好吧,当你在左连接的左侧放置一个条件(你的where子句)时,你基本上会使左连接无效(对于相关的表)。

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

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

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

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

答案 1 :(得分:0)

这有效

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