title: Correctly generating a unique invoice id
body: <p>I've been asked to clean up someone else's controller code, which generates an invoice, and I've run into something I don't know how to fix.  The code in question is as follows (this is using EF 6: Code First):</p>
  
  <pre><code>var invid = db.TransportJobInvoice.Where(c =&gt; c.CompanyId == CompanyId)
                  .Max(i =&gt; i.InvoiceId);
  var invoiceId = invid == null ? 1 : (int)invid + 1;
  </code></pre>
  
  <p>The code is supposed to generate an <code>invoiceId</code> based on the company the invoice is being created for.  So a small table of this might look as follows:</p>
  
  <pre><code>------------------------------
  | Id | CompanyId | InvoiceId |
  ------------------------------
  |  1 |         1 |         1 |
  ------------------------------
  |  2 |         1 |         2 |
  ------------------------------
  |  3 |         1 |         3 |
  ------------------------------
  |  4 |         2 |         1 |
  ------------------------------
  |  5 |         2 |         2 |
  ------------------------------
  </code></pre>
  
  <p>As you can see, the <code>invoiceId</code> would be generated based on the current number of invoices for the company in question.  However, I think it's reasonable to suggest that two threads could execute the query before this line is evaluated:</p>
  
  <pre><code>var invoiceId = invid == null ? 1 : (int)invid + 1;
  </code></pre>
  
  <p>which would result in the same <code>invoiceId</code> being generated for two different invoices.</p>
  
  <p>Is there a simple solution to this, possibly leveraging Entity Framework to do this automatically?</p>