I have a MS SQL table that I don’t have any control over and I need to write to. This table has a int primary key that isn’t automatically incremented. I can’t use stored procs and I would like to use Linq to SQL since it makes other processing very easy.
My current solution is to read the last value, increment it, try to use it, if I get a clash, increment it again and retry.
Something along these lines:
var newEntity = new Log() { ID = dc.Logs.Max(l => l.ID) + 1, Note = 'Test' }; dc.Logs.InsertOnSubmit(newEntity); const int maxRetries = 10; int retries = 0; bool success = false; while (!success && retries < maxRetries) { try { dc.SubmitChanges(); success = true; } catch (SqlException) { retries++; newEntity.ID = dc.Logs.Max(l => l.ID); } } if (retries >= maxRetries) { throw new Exception('Bummer...'); }
Does anyone have a better solution?
EDIT: Thanks to Jon, I simplified the max ID calculation. I was still in SQL thinking mode.
That looks like an expensive way to get the maximum ID. Have you already tried
? Maybe it doesn’t work for some reason, but I really hope it does…
(Admittedly it’s more than possible that SQL Server optimises this appropriately.)
Other than that, it looks okay (smelly, but necessarily so) to me – but I’m not an expert on the matter…