NHibernate QueryOver how to join on non declared relationship

巧了我就是萌 提交于 2019-11-27 03:41:53

问题


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

回答1:


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



回答2:


As of 5.1.0, it is possible to make hibernate generate an actual sql join on an undeclared (unmapped) relationship. E.g. all orders sorted by customer's spending:

var criteria = _session
    .CreateCriteria<Order>("order");

criteria
    .CreateEntityAlias(
        "customer",
        Restrictions.EqProperty("order.customerId", "customer._id"),
        JoinType.LeftOuterJoin,
        typeof(Customer).FullName)
    .AddOrder(new Order("customer._lifetimeSpending", ascending:false));

return criteria.List<Order>();

Also possible with QueryOver (sample from NHibernate docs):

Cat cat = null;
Cat joinedCat = null;

var uniquelyNamedCats = sess.QueryOver<Cat>(() => cat)
    .JoinEntityAlias(
        () => joinedCat,
        () => cat.Name == joinedCat.Name && cat.Id != joinedCat.Id,
        JoinType.LeftOuterJoin)
    .Where(() => joinedCat.Id == null)
    .List();


来源:https://stackoverflow.com/questions/7076556/nhibernate-queryover-how-to-join-on-non-declared-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!