简体   繁体   English

执行UPDATE并返回使用NHibernate CreateSQLQuery方法刚刚更新的记录?

[英]Execute UPDATE and return the record just updated using NHibernate CreateSQLQuery method?

How does one execute a SQL UPDATE statement and return the record just updated using NHibernate CreateSQLQuery method? 如何执行一条SQL UPDATE语句并返回使用NHibernate CreateSQLQuery方法刚更新的记录?

I am using the OUTPUT INSERTED.Id clause to get the id of just inserted value, I just get the id for simplicity. 我正在使用OUTPUT INSERTED.Id子句来获取刚刚插入值的ID,为简单起见,我仅获取ID。

My code is as following: 我的代码如下:

const string SQL =
            @"UPDATE Agent 
            SET Status = 'RESERVED' 
            OUTPUT INSERTED.Id 
            WHERE Id = (SELECT TOP 1 Id FROM Agent WHERE Status = 'ONLINE' ORDER BY StatusSetAt)";

var agentId = Session.CreateSQLQuery(SQL)
                     .AddScalar("Id", NHibernateUtil.String)
                     .List<string>()
                     .SingleOrDefault();

The correct agentId is returned by the List method, but the problem is that the data is not updated in the database. 正确的agentId由List方法返回,但是问题是数据库中的数据没有更新。

  • The SQL query works (it does the update when executing in SSMS). SQL查询有效(在SSMS中执行时会进行更新)。
  • SQL profiler shows the UPDATE query is sent to the database, but somehow the changes are not applied. SQL事件探查器显示UPDATE查询已发送到数据库,但是以某种方式未应用更改。

Is it by design that NH does not update the database on List methods? 是不是因为设计原因而导致NH不更新List方法上的数据库? is it possible to accomplish the same with ExecuteUpdate method? 是否可以使用ExecuteUpdate方法完成相同的操作? I can't find how to retrieve other value than the number of rows updated. 除了更新的行数之外,我找不到其他值。

Any help is much appreciated, thanks. 非常感谢任何帮助,谢谢。

I would suspect, there is (in your code) some transaction handling. 我怀疑, 在您的代码中有一些事务处理。 And, mostly becuase of this observation: 并且,主要是由于这种观察:

...SQL profiler shows the UPDATE query is sent to the database, but somehow the changes are not applied... ... SQL探查器显示UPDATE查询已发送到数据库,但是以某种方式未应用更改。

There will be ROLLBACK in this case. 在这种情况下将有ROLLBACK

So, try to check if there is some Unit of Work, or Web Request transaction management. 因此,请尝试检查是否存在某些工作单元或Web请求事务管理。 And most likely the above code, will be part of operation which is at the end not commited. 上面的代码很可能是操作的一部分,但最后仍未提交。

Why C# value seem to be updated, while transaction is rolled back? 为什么在事务回滚时C#值似乎已更新? Because the SQL statement is executed, the value is returned... and stored in C# variable. 因为执行了SQL语句,所以返回值...并存储在C#变量中。 And then, only on DB level all changes are reverted. 然后,仅在数据库级别还原所有更改。

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

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