简体   繁体   English

NHibernate加入临时表

[英]NHibernate JOIN to temp table

I want to do some work in SQL, populating a temp table, and then JOIN to that temp table using an NHibernate CreateSQLQuery to get my final results. 我想在SQL中做一些工作,填充一个临时表,然后使用NHibernate CreateSQLQuery联接到该临时表以获取最终结果。 We are on version 1.2.0.4000 of NHibernate and I seem to be having problems accessing a temp table in a later query, even though I'm in the same session (I believe this means I'm in the same SQL Session/Connection as well). 我们使用的是NHibernate的1.2.0.4000版本,即使我在同一会话中,我似乎也无法在以后的查询中访问临时表(我相信这意味着我与以下会话在同一SQL会话/连接中)好)。 Below is a simplified version of my code 下面是我的代码的简化版本

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
}

sessions get connections on demand, it is not guaranteed to get the same connection back. 会话按需获得连接,但不能保证获得相同的连接。 There are two possibilities to get the same connection every time: 每次都有两种可能获得相同的连接:

  • using sessionFactory.OpenSession(myConnection); 使用sessionFactory.OpenSession(myConnection); which ties the session to the provided connection. 将会话绑定到提供的连接。
  • implement IConnectionProvider which does the pooling of the connections 实现IConnectionProvider来进行连接池

Option 1 is definitly easier 选项1绝对容易

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM