Search code examples
nhibernatejoinqueryover

NHibernate QueryOver how to join on non declared relationship


How to do the following join to return Users who have access to a Company given a company id. The problem is there is no explicit relationship using a User object between UserAccess and User they simply join on the string property Username:

User(Username, Name)
UserAccess(Username, Company)
Company(Id)

Session.QueryOver<Company>()
        .Where(c => c.Id == companyId)
        .JoinQueryOver<UserCompanyAccess>(u => u.UserAccessList)
        .JoinQueryOver<User>(u => **Nope no property, just a string**

Solution

  • could be done with a subquery

    var subquery = QueryOver.Of<Company>()
        .Where(c => c.Id == companyId)
        .JoinQueryOver<UserCompanyAccess>(u => u.UserAccessList)
        .Select(uca => uca.UserName);
    
    var users = session.QueryOver<User>()
        .WithSubquery.WhereProperty(u => u.Name).In(subquery)
        .List();