【问题标题】:NHibernate JOIN to temp tableNHibernate JOIN 到临时表
【发布时间】:2013-10-07 15:30:44
【问题描述】:

我想在 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 在您的配置中调用哪个 RDBMS?
  • 您能否解释一下“...我在稍后的查询中访问临时表时似乎遇到了问题”?
  • 我在第一个查询中使用 SELECT INTO 创建临时表,并使用 ExecuteNonQUery 创建 ADO.NET 直接 SQL。在第二个查询中,使用相同的连接,我使用 NHibernate CreateSQLQuery 尝试加入临时表。当我在上面的代码示例中执行第二个(NHibernate)查询时,JOIN to #TempTable 失败,并在代码示例中的 cmets 中显示错误消息。即使我共享一个连接对象,我不认为查询在同一个 SQL 会话中运行,并且临时表超出范围。
  • 会话按需获取连接,不能保证返回相同的连接。除了使用 sessionFactory.OpenSession(myConnection); 将会话绑定到提供的连接。
  • 下次我想这样做时,我会尝试一下。我现在最终使用了不同的解决方案。 @Firo 你想发表你的评论作为答案吗?确认后我可以接受。

标签: c# sql sql-server nhibernate


【解决方案1】:

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

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

选项 1 肯定更容易

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-08
    • 1970-01-01
    • 2021-10-24
    • 2015-08-23
    • 2019-05-18
    • 1970-01-01
    • 2022-09-29
    • 1970-01-01
    相关资源
    最近更新 更多