Marco Bruggmann
Marco Bruggmann

Reputation: 625

How to delete and re-insert entities in linq?

I am having troubles inserting entities in linq after deleting them (without submitting the changes).

List<AlergiesPerPersonBE> AlergiesPerPerson = AlergiesPerPersonToInsert;

RepositoryFactory.GetAlergiesPerPersonRepository().DeleteWhere(x => x.PersonId == id);
RepositoryFactory.GetAlergiesPerPersonRepository().Insert(AlergiesPerPerson);

DataContextFactory.SubmitChanges();

Both (delete and insert) don´t submit any changes. They just InsertAllOnSubmit and DeleteAllOnSumbit.

The code works fine the first time. All the details are inserted properly. The second time that I run the same code, all rows of the db are deleted. The third time, all works fine. It works, then it doesn't, and so on.

Upvotes: 2

Views: 2215

Answers (3)

Kirk Broadhurst
Kirk Broadhurst

Reputation: 28728

Try

...DeleteWhere(x => x.PersonId == id); 
DataContextFactory.SubmitChanges();

...Insert(AlergiesPerPerson);
DataContextFactory.SubmitChanges();

There's no reason that you have to submit changes only once per unit of work. Note that this will still work with any transactions that you have.

Upvotes: 2

Milan Jaric
Milan Jaric

Reputation: 5646

There is dirty work around. Since you want to get rid of DataContext observer you will need to:

  1. serialize object or graph to memory stream.
  2. Then deserialize it back as new instance
  3. change ID to 0
  4. Attach new object to DataContext and submit changes.
  5. Delete previous

You can move this to CloneHelper static class so you can use it for any type

Upvotes: 0

Mick Walker
Mick Walker

Reputation: 3847

I think you will have to recreate the details again. The context is currently tracking this item as being 'deleted' even if save changes hasn't yet been called.

Upvotes: 2

Related Questions