【问题标题】:NH QueryOver - use properties of main query in subqueryNH QueryOver - 在子查询中使用主查询的属性
【发布时间】:2014-11-23 11:45:55
【问题描述】:

我正在尝试将以下 SQL 转换为 QueryOver:

Select 1 
From myTable mt 
Where mt.ForeignKey in (select ID from otherTable ot where ot.ID = R.ID)

我想在 EXISTS / NOT EXISTS 语句中使用这个子查询,例如:

select * from table R where .... AND EXISTS (query above)

目前我有类似的东西:

mainQuery.WithSubquery.WhereExists(QueryOver.Of<myTable>()
                    .Where(mt => mt.ForeignKey)
                    .WithSubquery.IsIn(QueryOver.Of<otherTable>().Where(c => c.Id == R.SomeId)));

我将此查询创建为要连接到主查询的子查询。 问题是别名为 R 的表是主查询调用的表,我不知道如何访问表(NHibernate 模型)R 的列(在上面的查询中无法访问),所以我的问题是:

如何从主查询中获取值并在子查询中使用它们。我认为这只能通过创建内联子查询(如在 mainQuery.WithSubquery.Where(..) 或类似)中实现,但我看不出最好的方法是什么。感谢您的帮助!

提前致谢!

【问题讨论】:

    标签: c# .net nhibernate queryover nhibernate-criteria


    【解决方案1】:

    诀窍是为父查询使用正确的别名:

    // the alias
    myTable R = null;
    
    mainQuery
        .WithSubquery
           .WhereExists(QueryOver
             .Of<myTable>( () => R) // the Alias in place
             .Where(mt => mt.ForeignKey)
             .WithSubquery.IsIn(QueryOver.Of<otherTable>().Where(c => c.Id == R.SomeId)));
    

    注意,不是完全确定 mainQuery 部分,但这里的一般解决方案是这样的:

    // I. the outer query ALIAS
    Employee emplyoee = null;
    
    // II. the subquery - using the alias
    var subQuery = QueryOver.Of<Contact>()
        .Select(x => x.ID)
        .Where(x => x.Related.ID == emplyoee.ID); // use alias
    
    // III. declare the outer query and use the above alias
    var query = session.QueryOver<Employee>(() => emplyoee) // declare alias
        .WithSubquery
            .WhereExists(subQuery); // put both together
    

    也可以查看this 了解更多想法

    【讨论】:

    • 感谢别名提示!在您的帮助下,通过查看我们代码库中的其他代码,我设法解决了这个问题!
    • 太棒了 ;) 享受 NHibernate,很棒的工具 ;)
    猜你喜欢
    • 1970-01-01
    • 2021-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多