简体   繁体   中英

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?

I am using the OUTPUT INSERTED.Id clause to get the id of just inserted value, I just get the id for simplicity.

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.

  • The SQL query works (it does the update when executing in SSMS).
  • SQL profiler shows the UPDATE query is sent to the database, but somehow the changes are not applied.

Is it by design that NH does not update the database on List methods? is it possible to accomplish the same with ExecuteUpdate method? 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...

There will be ROLLBACK in this case.

So, try to check if there is some Unit of Work, or Web Request transaction management. 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? Because the SQL statement is executed, the value is returned... and stored in C# variable. And then, only on DB level all changes are reverted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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