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<AlergiesPer开发者_开发技巧PersonBE> 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.
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.
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.
There is dirty work around. Since you want to get rid of DataContext observer you will need to:
- serialize object or graph to memory stream.
- Then deserialize it back as new instance
- change ID to 0
- Attach new object to DataContext and submit changes.
- Delete previous
You can move this to CloneHelper static class so you can use it for any type
精彩评论