NHibernate JOIN to temp table

本文关键字:table temp to JOIN NHibernate | 更新日期: 2023-09-27 18:34:11

我想在SQL中做一些工作,填充一个临时表,然后使用NHibernate CreateSQLQuery加入到该临时表以获得最终结果。我们使用的是 NHibernate 的 1.2.0.4000 版,即使我在同一会话中,我似乎在以后的查询中访问临时表时遇到了问题(我相信这意味着我也在同一个 SQL 会话/连接中)。 下面是我的代码的简化版本

public void Work()
{
    SqlConnection connection = (SqlConnection)Session.Connection;
    SqlCommand command = new SqlCommand
                     {
                         CommandType = CommandType.Text,
                         CommandText = "SELECT ID = 1 INTO #TempTable",
                         Connection = connection,
                     };
    if ( Session.Transaction != null && Session.Transaction.IsActive )
    {
        Session.Transaction.Enlist( command );
    }
    command.ExecuteNonQuery();
    // Simplified example, I should have a temp table #TempTable with 1 row containing the values ID = 1
    // trying to fetch a list of Account objects where ID exists in #TempTable.
    // At this point, I get an error "Invalid object name '#TempTable'."
    IList<Account> accounts = Session.CreateSQLQuery(@"
        SELECT *
          FROM Account a
          JOIN #TempTable tt
            ON a.ID = tt.ID")
        .AddEntity("a", typeof(Account))
        .List<Account>();
    // Do some work on accounts list
}

NHibernate JOIN to temp table

会话按需

获取连接,不保证恢复相同的连接。每次都有两种可能性获得相同的连接:

  • 使用将会话绑定到提供的连接的sessionFactory.OpenSession(myConnection);
  • 实现 IConnectionProvider 来执行连接的池化

选项 1 肯定更容易