1

每当我在上下文中执行对象时,我都会遇到并发异常的问题

我有这个:(我在网络表单上使用它顺便说一句)

using(entities ctx = new entities()){
    EventModel newEvent = new EventModel{
      Name = "name",
      Description = "description",
      CreationDate = DateTime.Now,
      CreatedBy = CurrentUserId()
    };

    try{
         ctx.EventModels.AddObject(newEvent);
         ctx.SaveChanges();
    }catch(OptimisticConcurrencyException ocex){
         if(ctx.ObjectStateManager.GetObjectStateEntry(newEvent).State == EntityState.Added){
               // proves that it is added.
         }
    }catch(Exception ex){
          throw ex;
    }
}

我现在不确定在哪里看。我尝试了 sql profiler,我唯一注意到的是它尝试插入新实例两次。就是这样。没有错误或类似的东西。

想法?

顺便说一句:这是我得到的错误

存储更新、插入或删除语句影响了意外数量的行 (0)。自加载实体后,实体可能已被修改或删除。刷新 ObjectStateManager 条目。

编辑:这是在探查器上执行的 sql。相同的 sql 执行了两次。

exec sp_executesql N'insert [dbo].[EventModel]([Name], [Description], [CreationDate], [CreatedBy]) values (@0, @1, @2, @3)', @0="Name", @1="description", @2="2013-01-31 11:41:41.5231006", @3="1"
4

1 回答 1

2

Solved the issue. It was because of the trigger on the table. When you do an addobject, entity framework expects an Id, and if it doesn't get that Id, it thinks that it's an update that have been modified by two instances which will then throw that error.

于 2013-02-04T18:03:41.377 回答