Tuesday, November 29, 2011

Discarding changes in LINQ memory

I was looking for a solution just like what I used to do with ADO.NET back in the days when LINQ was non-existent.

My issue was that when I received an exception while inserting a row in SQL db (due to duplicate value already present), I wanted to discard that insertion from the memory and carry out with the next insertion. The problem was that the last insertion error was not removed from memory.

Many people suggested recreation of the DataContext object, but that was not an option for me. After some "Googling", I found the link below which was helpful:

http://graemehill.ca/discard-changes-in-linq-to-sql-datacontext

Though I did something like the one below in the catch block, where "spmap" was the new object created for insertion.
datacontext.tablename.DeleteOnSubmit(spmap);
Works for me! :)

1 comment:

Bart Janson said...

Works like a charm, thanks!