Primary key already exists when saving new record using EF6

0

I have been using this logic for a month and it has stopped working recently.

var tool = new Tool() { ToolNumber = toolNumber.Trim(), Description = description.Trim() };
context.AddToTools(tool);
context.SaveChanges();

AddToTools just looks like this:

    public void AddToTools(Tool tool)
    {
        base.AddObject("Tools", tool);
    }

I get the error on context.SaveChanges();

System.Data.Entity.Core.UpdateException HResult=0x80131501 Message=An error occurred while updating the entries. See the inner exception for details.

The Inner Exception:

{"Violation of PRIMARY KEY constraint 'PK_Tool'. Cannot insert duplicate key in object 'dbo.Tool'. The duplicate key value is (0).\r\nThe statement has been terminated."}

When I check the the value the tool.ID value is 0 and there is already a ID of 0 in the table so the exception is correct.

It seems like some kind of update, OS update or SqlServer update or something has broken it.

Why is my insert to the table not working?

c#
entity-framework-6
asked on Stack Overflow Jun 21, 2019 by Eric Snyder

1 Answer

0

Per @Bosco above:

"Either the primary Key is no longer incremental, as the Inner Exception stated duplicate key is 0. You need to set the ok to auto increment"

Somehow the Identity property had been changed to no in the table definition. Changed it to yes and all is well.

answered on Stack Overflow Jun 21, 2019 by Eric Snyder

User contributions licensed under CC BY-SA 3.0