What is the best way to manually generate Primary Keys in Entity Framework 4.1 Code First?
I am programming ASP.NET MVC 3 and I use a repository pattern.
I currently generate keys in a sequential order by using the code below:
'Code First Class
Public Class Foo
<Key()>
<DatabaseGenerated(DatabaseGeneratedOption.None)>
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
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.
Is this a good way, or is there any better?
Please not that I CANNOT (and will not) use a database generated identity field!
Here is what I ended up using. This code is based on the post by Ladislav Mrnka, but modified to work with DbContext.
Model for storing sequence information (do not forget to add it as a DBSet in your context).
Initilize database and create a Stored Procedure to get and auto increment sequences.
Get a new key (iNewKey) for Entity Foo by running the stored procedure.