Graeme Hill's Dev Blog

LINQ to SQL Gotcha #6: Delete, Save, Insert, CRASH

Star date: 2010.091

If you keep the same entity around after it has been deleted and SubmitChanges() is called then you can run into an InvalidOperationException if you try to insert it again.

var data = new DataClasses1DataContext();
var user = new User() { userName = "foo", password = "bar" };

data.Users.InsertOnSubmit(user);
data.SubmitChanges();

data.Users.DeleteOnSubmit(user);
data.SubmitChanges();

data.Users.InsertOnSubmit(user);
data.SubmitChanges();

Here you will actually get an exception on the second InsertOnSubmit() because the data context remembered the entity and will no longer allow you to attach it for some reason. Once an entity has been deleted from a data context it can never go back. To get around this you need to either insert the entity to a different data context or copy the data to a new instance of the same entity class and then insert it. This has been confirmed here.

Note: You are free to call DeleteOnSubmit() and then InsertOnSubmit() all you want as long as you never call SubmitChanges().

comments powered by Disqus