Search code examples
nhibernatequeryover

NHibernate QueryOver and selecting rows where a propery is an ILIST and the list count >= 1


I would like to select rows for which the property Items which is an IList has rows itself. In SQL its easy count >= 1 but in NHibernate it eludes me.

Tried many ways

public class Sale
{
    private IList<Items> _items;

    public Sale()
    {
        _items = new List<Item>();
    }

    public Guid SaleId { get; set; }
    public string SaleNumber { get; set; }
    public string Location { get; set; }
    public DateTime? SaleDateTime { get; set; }

    public IList<Item> Items => _items;
}

public class Item
{
    public Guid ItemId { get; set; }
    public string description { get; set; }
}

        var testdata = _session.QueryOver<Sale>()
            .Where(Restrictions.Ge(
                Projections.Property<Sale>
                (m => m.Items.Count), 1))
            .ReadOnly()
            .ListAsync();

Count is unrecognized


Solution

  • Technically if you did an inner join you wouldn't receive any Sale records back that do not have any Item records.

    So as a really simple QueryOver you could do:

    var sales = session.QueryOver<Sale>()
      .Inner.JoinQueryOver(x => x.Items)
      .Select(Projections.RootEntity())
      .TransformUsing(Transformers.DistinctRootEntity)
      .List();
    

    This is the resulting SQL:

    SELECT this_.SaleId as saleid1_1_0_, 
      this_.SaleNumber as salenumber2_1_0_, 
      this_.Location as location3_1_0_, 
      this_.SaleDateTime as saledatetime4_1_0_ 
    FROM Sale this_ 
     inner join Item item1_ on this_.SaleId=item1_.SaleId