插入到表中而不是从实体数据框架触发的错误 [英] error when inserting into table having instead of trigger from entity data framework

查看:137
本文介绍了插入到表中而不是从实体数据框架触发的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用实体框架4,在表中使用实体框架插入新记录,而不是在表具有标识列时插入触发器,而是使用触发器来修改插入的值之一对于某些逻辑,实体框架引发异常存储更新,插入或删除语句影响了意外数量的行(0)。实体可能已被修改或删除,因为实体被加载刷新ObjectStateManager条目。

I'm using entity framework 4 , on inserting a new record using entity framework in a table that have instead of insert trigger while the table has an identity column , the instead of trigger is used to modify one of the inserted value according to certain logic ,Entity framework raises exception "Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries".

任何人都可以帮助解决这个异常?

Can any one help how to get around this exception?

推荐答案

使用Entity Framework 4.1, Ladislav发布的解决方案在触发器结尾处添加了一个Scope_Identity()选项,解决了我的问题。我完整地复制了这里的整个触发器创建。通过这个触发器defenition,我可以使用context.SaveChanges()向表中添加行。

Using Entity Framework 4.1, the solution posted by Ladislav to add a Select of Scope_Identity() to the end of the trigger body solved the problem for me. I have copied the entire trigger creation here for completeness. With this trigger defenition I was able to add rows to the table using context.SaveChanges().

ALTER TRIGGER [dbo].[CalcGeoLoc]
   ON  [dbo].[Address]
   INSTEAD OF INSERT
AS 
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT OFF;

-- Insert statements for trigger here
INSERT INTO Address (Street, Street2, City, StateProvince, PostalCode, Latitude, Longitude, GeoLoc, Name)
SELECT Street, Street2, City, StateProvince, PostalCode, Latitude, Longitude, geography::Point(Latitude, Longitude, 4326), Name 
FROM Inserted;

select AddressId from [dbo].Address where @@ROWCOUNT > 0 and AddressId = scope_identity();
END

编辑处理计算值(感谢Chris摩根在评论中):

Edit for handling computed values (Thanks to Chris Morgan in the comments):

如果表中还有其他计算值,您也必须将它们包含在SELECT中。例如,如果你有一个使用 GETDATE() CreatedDate 列,你可以这样选择:

If you have any other computed values in the table you will have to include them in the SELECT as well. For example if you had a CreatedDate column that uses GETDATE() you would make the select like this:

SELECT [AddressId], [CreatedDate] from [dbo].Addresses where @@ROWCOUNT > 0 and AddressId = scope_identity();

这篇关于插入到表中而不是从实体数据框架触发的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆