Search code examples
nhibernatehibernateicriteriacriteria-api

NHibernate: How to exclude a class which is part of a join using the Criteria API


I am still new to Hibernate and am attempting to use it for a web site I have inherited. Unfortunately that means sometimes the db schemas don't always make sense.

With that said, I am trying to build the following HQL query using the Criteria API

from TableB b where b.id = :id and b.TableAProperty.UserId = :userId

The above HQL statement generate SQL which will select and return TableB only which is what I want to happen. However using the Critera API statements shown below, the generated SQL statement selects the fields for TableB and TableA.

DataProvider.Session
    .CreateCriteria<TableB>()
    .Add(Expression.Eq("Id", id))
    .CreateCriteria("TableA")
    .Add(Expression.Eq("UserId", userId))
    .UniqueResult<TableB>()
    ;

In a perfect world I could update the db schemas to make more sense, but alas I cannot. Any help on this would be greatly appreciated.


Solution

  • Your question doesn't show the classes associated with TableA and TableB, so I'm going to assume that the classes are TableA and TableB and that TableB has a property called TableA.

    DataProvider.Session
        .CreateCriteria<TableB>()
        .Add(Expression.Eq("Id", id))
        .CreateAlias("TableA", "a")
        .Add(Expression.Eq("a.UserId", userId))
        .UniqueResult<TableB>();