title: What is the best way to manually generate Primary Keys in Entity Framework 4.1 Code First
body: <p>What is the best way to manually generate Primary Keys in Entity Framework 4.1 Code First?</p>
  
  <p>I am programming ASP.NET MVC 3 and I use a repository pattern.</p>
  
  <p>I currently generate keys in a sequential order by using the code below:</p>
  
  <pre><code>'Code First Class
  Public Class Foo
      &lt;Key()&gt;
      &lt;DatabaseGenerated(DatabaseGeneratedOption.None)&gt;
      Public Property iId As Integer
  
      Public Property sBar As String
  End Class
  
  'Context Class
   Public Class FooBarContext : Inherits DbContext
       Public Property Foos As DbSet(Of Foo)
   End Class
  
  'Get the current Id
  
  'Part of code in repository that stores Entity Foo.
  Dim iCurrId as Integer = (From io In context.Foo
                           Select io.iId()).Max
  
  Dim iNewId as Integer = iCurrId + 1
  
  Foo.iId = iNewId
  </code></pre>
  
  <p>My consern is (however unlikely) that two (or more) users will try to save an entity Foo at the same time and with therefore will get the same ID and the insert will fail.</p>
  
  <p>Is this a good way, or is there any better?</p>
  
  <p>Please not that I CANNOT (and will not) use a database generated identity field!</p>