如何使用NHibernate QueryOver而不是Linq创建此查询?

时间:2013-06-21 13:06:27

标签: nhibernate nhibernate-criteria

我需要使用QueryOver而不是Linq,但我正在努力重新创建以下查询:

public IQueryable<AuctionItem> GetLiveAuctionItems(){
    repository.Query<AuctionItem>().Where(IsInActiveAuction()
}

 public static Expression<Func<AuctionItem, bool>> IsInActiveAuction()
        {
            var now = SystemTime.Now();
            var expression = PredicateBuilder.True<AuctionItem>();
            return expression.And
                (x => x.Lots.Any(
                    z => z.Auction.StartTime < now && z.Auction.EndTime > now && !z.DateWithdrawn.HasValue
                         && z.DateApproved.HasValue));
        }

我意识到这会创建子查询,但是当我尝试使用查询创建时,我会收到错误,说明需要进行投影。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

快速草稿,明确如何步骤。第一部分subquery可能如下所示:

QueryOver<Lot> subQuery =
    QueryOver.Of<Lot>(() => lot)
    // Lot WHERE
    .WhereRestrictionOn(() => lot.DateWithdrawn).IsNull
    .AndRestrictionOn(() => lot.DateApproved).IsNotNull
    // Auction JOIN
    .JoinQueryOver<Auction>(l => l.Auction, () => auction)
        // Auction WHERE
        .Where(() => auction.StartTime < now)
        .Where(() => auction.EndTime > now)
    // AuctionItem.ID SELECT == projection
    .Select(Projections.Property(() => lot.AuctionItem.ID))
    ;

因此,这将返回符合我们的搜索条件的AuctionItem.ID。我们可以像这样使用它:

AuctionItem auctionItem = null;
var query = session.QueryOver<AuctionItem>(() => auctionItem)
    .WithSubquery
    .WhereProperty(() => auctionItem.ID)
    .In(subQuery)
    ...