NHibernate QueryOver how to join on non declared relationship

jenson-button-event picture jenson-button-event · Aug 16, 2011 · Viewed 7.5k times · Source

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**

Answer

Firo picture Firo · Aug 16, 2011

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();