2013-10-07 41 views
0

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

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 
} 
+0

其中在配置的RDBMS NHibernate的呼吁一直到? –

+0

微软SQL服务器 – Dude0001

+0

你能解释一下“......我似乎有问题在以后的查询中访问临时表”吗? –

回答

2

会话按需获取连接,但不保证获得相同的连接。 有两种可能每次都得到相同的连接:

  • 使用sessionFactory.OpenSession(myConnection);它关系的会议所提供的连接。
  • 实现IConnectionProvider它执行连接池

选项1是definitly容易