Question

I want the outcome to be a single sql statement. I have the following structure:

public class B
{
    public virtual int Id { get; set; }
    public virtual int BNumber { get; set; }
}
public class A
{
    public virtual int Id { get; set; }
    public virtual IList<B> Bs { get; set; }
    public virtual int ANumber { get; set; }
}

If I have a detached criteria that filters A's by numbers higher then 6:

DetachedCriteria.For<A>().Add(Restrictions.Gt("ANumber", 6))
                         .Add(Subqueries.???).List<A>();

I want to add a filter that will return only A's that contains B's with Number lower then 5. How do I do it? I want this as generic as possible so I can reuse it in multiple places.

Was it helpful?

Solution

DetachedCriteria.For<A>()
    .Add(Restrictions.Gt("ANumber", 6))
    .CreateCriteria("Bs")
        .Add(Restrictions.Lt("BNumber", 5))
    .List<A>();

Update: having an Or from different subqueries

DetachedCriteria.For<A>()
    .Add(Restrictions.Gt("ANumber", 6))
    .CreateAlias("Bs", "b")
    .CreateAlias("Cs", "c")
    .Add(Restrictions.Or(
        Restrictions.Lt("b.Number", 5),
        Restrictions.Lt("c.Number", 5))
    .List<A>();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top