Nhibernate SQLQuery 作为子查询

Nhibernate SQLQuery as Subquery

如何使用本机 sqlquery (session.CreateSqlQuery) 作为另一个 QueryOver 中的过滤子查询:

                // Get  ids
            var idsq = _session.CreateSQLQuery(
                "select Id from [dbo].[SomeFunction](:parameter)")
                .AddEntity(typeof(long)).
                SetParameter("parameter", folderId);

            // get entities by filtering where in (subquery)
            MyEntity entityAlias = null;
            var listOfEntities = await _session.QueryOver(() => entityAlias).
                Where(x=>x.Id).IsIn(idsq).
                OrderBy(x => x.Name).Asc.
                ListAsync(cancelToken).ConfigureAwait(false);

您不能轻易混合各种风格的 NHibernate...您可以做什么:

var crit = new SQLCriterion(SqlString.Parse("{alias}.Id IN (select Id from [dbo].[SomeFunction](?))"),
                                    new object[] { folderId },
                                    new IType[] { NHibernateUtil.Int64 });

然后:

var listOfEntities = await _session.QueryOver(() => entityAlias)
    .Where(crit)
    .OrderBy(x => x.Name).Asc

请注意我如何更改文本查询添加 {alias}.Id IN (...)