Using the SQL 2008 R2 release database in November and the Azure.net 4.0 Beta 2 workspace role application, the work role collects data and inserts it into a single SQL table with a single identifier column. Since it is likely that several instances of this working role will be involved, I created an "Insert instead of a trigger" into the SQL table instead of the SQL query. The trigger executes the Upsert function using the SQL Merge function. Using T-SQL, I was able to verify the correct insertion instead of the trigger functions, new rows were inserted when updating existing rows. This is the code for my trigger:
Create Trigger [dbo].[trgInsteadOfInsert] on [dbo].[Cars] Instead of Insert as begin set nocount On merge into Cars as Target using inserted as Source on Target.id=Source.id AND target.Manufactureid=source.Manufactureid when matched then update set Target.Model=Source.Model, Target.NumDoors = Source.NumDoors, Target.Description = Source.Description, Target.LastUpdateTime = Source.LastUpdateTime, Target.EngineSize = Source.EngineSize when not matched then INSERT ([Manufactureid] ,[Model] ,[NumDoors] ,[Description] ,[ID] ,[LastUpdateTime] ,[EngineSize]) VALUES (Source.Manufactureid, Source.Model, Source.NumDoors, Source.Description, Source.ID, Source.LastUpdateTime, Source.EngineSize); End
In the working role, I use the Entity Framework for the object model. When I call the SaveChanges method, I get the following exception:
OptimisticConcurrencyException 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.
I understand that it looks like SQL is not reporting an IdentityScope return for each new inserted / updated row. Then EF considers that the rows were not inserted and the transaction was ultimately not completed.
What is the best way to handle this exception? Perhaps using OUTPUT from SQL merge function?
Thanks! -Paul
triggers entity-framework sql-server-2008-r2 .net-4.0-beta-2
PaulWaldman
source share