0

How Can use a native sqlquery (session.CreateSqlQuery) as filtering subquery in another 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);
5
  • I don't think you can do it like this - you'd have to return the result of idsq to the client, which is probably a bad idea as you don't know how large it is. You can probably add [dbo].[SomeFunction] to a custom sql dialect and use it that way - see nhibernate.info/blog/2009/03/13/… or ayende.com/blog/1720/using-sql-functions-in-nhibernate Commented May 15, 2018 at 13:03
  • I don't think you can easily do it... The "direction" should be: .WithSubquery.WhereProperty(x => x.Id).In(...) but then the In requires a QueryOver query. Commented May 15, 2018 at 13:04
  • I dont' know why NH cant handle this case, because it should be easy to embed native SQL inside a where in () in generated sql or even join to table valued sql function Commented May 15, 2018 at 13:09
  • Also see andrewwhitaker.com/blog/2014/08/15/… which suggests using Projections.SqlFunction Commented May 15, 2018 at 13:10
  • 1
    @DavidKemp Thanks, My problem solved by Accepted answer Commented May 15, 2018 at 13:59

1 Answer 1

3

You can't easily mix various styles of NHibernate... What you can do:

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

and then:

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

Note how I changed the text query adding {alias}.Id IN (...)

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks So Much, It worked perfectly, I think this is a must to have trick for legacy database
NHibernate use function in another one to many query for a One-To-Many association between MyEntity and another child collection table, Do you have any suggestion to make it one time call without producing Cartesian production result
@HamidNaeemi Unclear what you are asking... and it seems to be quite complex... you should make another question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.