且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

OptimisticConcurrencyException - SQL 2008 R2而不是使用实体框架插入触发器

更新时间:2023-02-05 08:01:30

如您所怀疑的那样,问题是任何插入到具有Identity列的表格中都会立即然后选择一个scope_identity()来填充实体框架中的关联值。而不是触发器会导致错过第二个步骤,这会导致0行插入错误。

As you suspected, the problem is that any insertions into a table with an Identity column are immediately followed by a select of the scope_identity() to populate the associated value in the Entity Framework. The instead of trigger causes this second step to be missed, which leads to the 0 rows inserted error.

我在这个***线程,建议添加在触发结束的下一行(如果项目不匹配,插入执行)。

I found an answer in this *** thread that suggested adding the following line at the end of your trigger (in the case where the item is not matched and the Insert is performed).

select [Id] from [dbo].[TableXXX] where @@ROWCOUNT > 0 and [Id] = scope_identity() 

我用Entity Framework 4.1测试了这个,它解决了我的问题我已经将我的整个触发器创建在这里复制完整。通过这个触发器defenition,我可以通过向上下文添加地址实体来添加行,并使用context.SaveChanges()。

I tested this with Entity Framework 4.1, and it solved the problem for me. I have copied my entire trigger creation here for completeness. With this trigger defenition I was able to add rows to the table by adding Address entities to the context and saving them 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