1

I'm having problems with doing a concurrency exception whenever I do an Object on my context

I have this: (I'm using it on webforms btw)

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;
    }
}

I'm not really sure where to look at now. I tried the sql profiler and the only thing I noticed is that it tries to insert the new instance twice. That's it. No error or anything like that.

Thoughts?

BTW: This is the error I get

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.

EDIT: This is the sql executed on the profiler. Same sql executed twice.

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"
gdubs
  • 2,724
  • 9
  • 55
  • 102
  • It would help if you posted the actual SQL from profiler, but it looks like maybe you have a concurrency token set up incorrectly? – Craig Stuntz Jan 31 '13 at 20:15
  • checl http://stackoverflow.com/questions/1836173/entity-framework-store-update-insert-or-delete-statement-affected-an-unexpec – spajce Jan 31 '13 at 20:22
  • that's actually the reason why I checked with sql profiler to see if there are any updates. But there are no updates, both of them are inserts (identical ones too). – gdubs Jan 31 '13 at 20:34

1 Answers1

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.

gdubs
  • 2,724
  • 9
  • 55
  • 102