user1855165
user1855165

Reputation: 289

EF - Save Changes - How to fix VIOLATION OF PRIMARY KEY constraint

I am using Entity Framework to add data into a table in sql. I have the below class and method to add the new records. But I am getting the below error.

SqlException: Violation of PRIMARY KEY constraint 'PK__Users__3214EC27E90BFE7E'. Cannot insert duplicate key in object 'dbo.Users'. The duplicate key value is (0). The statement has been terminated.

public partial class User
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }
    public string Name { get; set; }

    public string Surname { get; set; }

}        


    public void InsertUser(MyEvent e)
    {
        using (var db = CreateInstance())
        {
            var users = db.Set<User>();
            users.Add(new User
            {
                Name= e.Name,
                Surname= e.Surname                    
            });
            db.SaveChanges();
         }
      }

How can EF auto-increment the ID in the table?

Upvotes: 1

Views: 1753

Answers (2)

PiotrS
PiotrS

Reputation: 188

It should be the SQL server itself incrementing the PK, not the EF. If you have multiple EF clients inserting data into the DB at the same time, it would be difficult to ensure the PK is incremented correctly. With SQL it is much easier, all you need to do is set the PK column as identity with auto-increments.

If the PK column is row_id, you can define it like this via scripting:

[row_id] [int] IDENTITY(1,1) NOT NULL

Or, if you create the table using SSMS designer, then in the column properties set Identity Specification as:

Is Identity = Yes
Identity Increment = 1
Identity Seed = 1

Upvotes: 2

Majid Parvin
Majid Parvin

Reputation: 5062

Remove the DB and just define as:

public int Id { get; set; }

without any Data Annotations

Upvotes: 0

Related Questions