Search code examples
sqlnhibernatenhibernate-criteriaqueryover

NHibernate: Reverse Exists Criteria


I'm querying Foo. Foo doesn't have an IList<FooBar> property (unfortunately). FooBar has a Foo property (but not a Bar), Bar has an IList<FooBar>. I need all the Foos where exists a FooBar which has a corresponding Bar with that Bar's Date field equal to today.

I'm not really a pro with Criteria API, but it's not my choice to use it or not.


Edit: I tried the same with the QueryOver API and got this far:

 var q1 = session.QueryOver<Foo>()
                 .WithSubquery.WhereExists<Bar>(
                     session.QueryOver<Bar>()
                            .Where(b => b.Date == DateTime.Today)
                            .JoinQueryOver<FooBar>(b => b.FooBars)
                            .Where(fb => fb.Foo == /*???*/ ))
                 .List<Foo>();

What do I write in the place of /*???*/?


Solution

  • Early disclaimer - I do not have NHibernate installed right now, so this is untested, but I would approach it with something like this:

    var foos = session.CreateCriteria<Bar>("bar")
                          .CreateCriteria("FooBars", "foobar")
                          .Add(
                             Restrictions.Eq(
                                "bar.Date", 
                                DateTime.Today.ToString("d", CultureInfo.InvariantCulture)
                             ))
                          .SetProjection(Projections.Property("foobar.Foo"))
                          .List<Foo>();