Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 5845991
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 22, 20262026-05-22T12:30:50+00:00 2026-05-22T12:30:50+00:00

What is the best way to manually generate Primary Keys in Entity Framework 4.1

  • 0

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!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-22T12:30:50+00:00Added an answer on May 22, 2026 at 12:30 pm

    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).

    <Table("tSequences")>
    Public Class Sequence
        <Key()>
        <DatabaseGenerated(DatabaseGeneratedOption.None)>
        <Display(Name:="Model name", Order:=1)>
        Public Property sModelName As String
    
        <Required()>
        <Display(Name:="Current Primary key value", AutoGenerateField:=False, Order:=2)>
        Public Property iCurrentPKeyValue As Integer
    End Class
    

    Initilize database and create a Stored Procedure to get and auto increment sequences.

    Public Class DBInitializer
        Inherits CreateDatabaseIfNotExists(Of Context)
    
        Protected Overrides Sub Seed(context As Context)
            'Create stored procedure to hold
            Dim sStoredProcSQL As String = "CREATE PROCEDURE [dbo].[spGetNextSequenceValue]" & vbCrLf & _
                                            "@sModelName VARCHAR(30)" & vbCrLf & _
                                            "AS BEGIN" & vbCrLf & _
                                            "DECLARE" & vbCrLf & _
                                            "@Result INT" & vbCrLf & _
                                            "UPDATE [dbo].[tSequences] WITH (ROWLOCK, UPDLOCK)" & vbCrLf & _
                                            "SET @Result = iCurrentPKeyValue = iCurrentPKeyValue + 1" & vbCrLf & _
                                            "WHERE sModelName = @sModelName" & vbCrLf & _
                                            "RETURN @Result" & vbCrLf &
                                            "END"
    
            context.Database.ExecuteSqlCommand(sStoredProcSQL)
        End Sub
    End Class
    

    Get a new key (iNewKey) for Entity Foo by running the stored procedure.

    Dim iNewKey As Integer
    
    Using scope = New TransactionScope(TransactionScopeOption.RequiresNew, New TransactionOptions() With { _
        .IsolationLevel = IsolationLevel.ReadCommitted _
        })
        iNewKey = context.Database.SqlQuery(Of Integer)("DECLARE @return_value int" & vbCrLf & _
                                                        "EXEC @return_value = [dbo].[spGetNextSequenceValue]" & vbCrLf & _
                                                        "@sModelName = 'Foo'" & vbCrLf & _
                                                        "SELECT 'Return Value' = @return_value").ToList().First()
    'Indicate that all operations are completed.
        scope.Complete()
    
        context.SaveChanges()
    End Using
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

What is the best way to generate a manually int primary key with mysql?
Possible Duplicate: What is the best way to compare two entity framework entities? I
What is the best way to include an html entity in XSLT? <xsl:template match=/a/node>
What is the best way to iterate through a strongly-typed generic List in C#.NET
I have run into my first dissapointment with Entity Framework 4. It turns out
I am trying to figure out the best way to deal with this. First,
What is the best way to verify/test that a text string is serialized to
What is the best way of creating an alphabetically sorted list in Python?
What is the best way to authorize all users to one single page in
What is the best way to store international addresses in a database? Answer in

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.