抛出这个异常的原因并不惟一,所以此方法并不通用。在nhibernate中,默认认为,数据实体的增删改操作只影响数据库中的一行记录,如果ExecuteNonQuery操作返回的数字不为1,则会抛出此错误。比如我的一个项目中,无限级分类的增删改操作都由存储过程来实现,在表中有一列orders字段用作数据记录的排序用,增删改操作时,可能会有多行记录需要更改。我的解决办法是,在存储过程中需要更改的其它记录前设置 set nocount on,之后设置 set nocount off ,最后执行目的记录(此记录惟一)的增删改操作。补上一个示例存储过程:
CREATE PROCEDURE CreateDepartment
(
@parentId int=0,
@Name nvarchar(30)='',
@DepartmentID int out
)
as
set nocount on
declare @parentStr nvarchar(1000)
declare @maxOrders int
declare @rootId int
declare @depth int
declare @orders int
if @parentId=0
begin
set @parentStr=''
set @Depth=0
select @rootId=Max(rootId) FROM department WHERE ParentId=0
if isnumeric(@rootid)=0 set @rootid=0
if isnumeric(@maxorders)=0 set @maxorders=0
set @RootId=@RootId+1 --添加1
select @maxOrders=max(orders) from department where rootid<@rootid
end
else
begin
select @parentStr=ParentStr,@RootId=RootId,@Depth=Depth FROM department WHERE DepartmentID=@parentId
select @maxorders=max(Orders) from department where charindex(','+cast(@parentid as nvarchar)+',',','+parentstr+',')>0
if isnumeric(@maxorders)=0 select @maxorders=orders from department where DepartmentID=@parentid
set @parentStr=@parentStr+','
if @parentStr='0,' set @parentStr=''
end
set @parentstr=@parentstr+LTrim(cast(@parentId as varchar(10)))
set @depth=@depth+1
set @orders=@maxOrders+1
update department set childs=childs+1 where departmentid=@parentid
update department set Orders=orders+1 where orders>=@orders
set nocount off
insert department(Name,ParentId,ParentStr,RootId,childs,Depth,Orders)VALUES(@name,@ParentId,@ParentStr,@RootId,0,@Depth,@Orders)
set @DepartmentID=@@IDENTITY
GO