title: Correctly incrementing values using Linq to SQL
body: <p>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.</p>
  
  <p>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. </p>
  
  <p>Something along these lines:</p>
  
  <pre><code>var newEntity = new Log()
  {
      ID = dc.Logs.Max(l =&gt; l.ID) + 1,
      Note = "Test"       
  };
  
  dc.Logs.InsertOnSubmit(newEntity);
  
  const int maxRetries = 10;
  int retries = 0;
  
  bool success = false;
  while (!success &amp;&amp; retries &lt; maxRetries)
  {               
      try
      {                                                           
          dc.SubmitChanges();
          success = true;
      }
      catch (SqlException)
      {
          retries++;
          newEntity.ID = dc.Logs.Max(l =&gt; l.ID);                  
      }
  }           
  if (retries &gt;= maxRetries)
  {
      throw new Exception("Bummer...");
  }
  </code></pre>
  
  <p>Does anyone have a better solution?</p>
  
  <p>EDIT: Thanks to <a href="https://stackoverflow.com/questions/385809/correctly-incrementing-values-using-linq-to-sql#385814">Jon</a>, I simplified the max ID calculation. I was still in SQL thinking mode.</p>