NHibernate and TooManyRowsAffectedException(转载)

本文讨论了在使用NHibernate框架时遇到的TooManyRowsAffectedException异常,并详细解释了该异常产生的原因,即触发器导致更新操作返回的受影响行数超出预期。最后给出了通过设置SET NOCOUNT ON/OFF来解决这一问题的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Today I received a log of an error in a windows service that runs some scheduled actions, the error was TooManyRowsAffectedException and it is thrown by nhibernate when a session is flushed. The exact message said Unexpected row count: 2; expected: 1 , after a little moment of confusion I immediately realize that the problem is due to a trigger.

I modified a table to keep a log of all modifications of every row, and I did this with a simple trigger that, for each update, saves the last value of each modified row in an history table. Since the trigger runs in the same context of the update operation, when you update a row, the trigger fired, insert a row in history table and the whole update operation returns 2 as the number of affected rows. NHibernate check the affected row count to verify that the row was really updated by the UPDATE statement, when he saw a rowcount of 2 he throws exception because something was wrong since it issue an update of a single row.

The obvious solution is to issue a SET NOCOUNT ON at the beginning of the trigger and a SET NOCOUNT OFF at the end. This is a good practice, because in this way the trigger does not affect the number of affected rows. After all the trigger should be completely transparent to the application, and this is the best way to achieve this result.

From:http://www.codewrecks.com/blog/index.php/2009/03/25/nhibernate-and-toomanyrowsaffectedexception/

转载于:https://www.cnblogs.com/ajian/archive/2010/05/18/1738079.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值