Search code examples
nhibernatenhibernate-criteria

How would one create this query using NHibernate QueryOver instead of Linq?


I need to use QueryOver instead of Linq but am struggling to recreate the following query:

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));
        }

I realise this creates subqueries but when I try to create using queryover I get errors stating projections needed.

Any help is much appreciated.


Solution

  • A quick draft with a clear how to steps. The first part, the subquery could look like this:

    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))
        ;
    

    So, this will return the AuctionItem.ID, which does meet our seraching criteria. And we can use it like this:

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