0

I'm trying to design a rollback changes system. I'm tracking old record values when a record id modified or deleted and then I'm using that values to re-insert it when user choose to rollback it...

editions rollback are working as expected.

deletions are not... because when I attach the entity to DBContext it has the old Id but when I execute DbContext.SaveChanges(); the Id is replaced per a new one(Auto Incremented)

Here is the sample code:

var model = JsonConvert.DeserializeObject(oldValues.OldData, type);
DbSet mySet = this.Set(type);
mySet.Attach(model);
this.Entry(model).State = oldValues.AuditType == 0 ? EntityState.Modified : EntityState.Added;
base.SaveChanges();

into model.Id I can see the correct Id before save but after it EF changes it per a new one.

is there anyway to set temporally to keep the current Id instead of generate a new one?

I tried many solutions but none of them works.

Thanks

1 Answers1

0

To disable the Auto Generated Id, you have to run this command in SQL:

SET IDENTITY_INSERT [<schema>].[<TableName>] ON;  

Then you can insert whatever value you want for the PK, assuming it is still available. However, I don't think EF has a way to do this from code.

I'm not entirely sure this would work, but, in theory, you could run some ad-hoc SQL right before save-changes on a transaction you create and then see if EF will take it.

If that doesn't work, then try this:

ALTER TABLE theTableInQuestion AUTO_INCREMENT=1234

EIDT: Or try this approach:

How can I force entity framework to insert identity columns?

Community
  • 1
  • 1
Daniel Lorenz
  • 4,178
  • 1
  • 32
  • 39