dalegor
dalegor

Reputation: 13

Violation of primary keys when creating a new record with Entity Framework

Utter greenhorn here! It has already devoured me a few hours, but - I hope - for you it will be a piece of cake. I have had to first create a database (containing a single table book) and then automatically implement a basic CRUD functionality with Entity Framework. The table does have its primary key defined!

My problem apparently lies in the way IDs are being generated. Starting with an empty database, I got no exception adding the first record, but cannot add the next one and the db.SaveChanges() instruction within Create function of BookController throws DbUpdateException:

[HttpPost]
public ActionResult Create(book book)
{
    if (ModelState.IsValid)
    {
        db.book.Add(book);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(book);
}

The internal exception goes as follows:

Violation of PRIMARY KEY constraint 'PK_book'. Cannot insert duplicate key in object 'dbo.book'. The statement has been terminated.

I have changed the part of the generated context by adding two annotations before the ID definition, but it still doesn't work.

public partial class book
{
    [Key] // added
    [DatabaseGenerated(DatabaseGeneratedOption.Computed)] // added
    public int ID { get; set; }

    public string title { get; set; }
    public string author { get; set; }
    public Nullable<int> pages { get; set; }
    public Nullable<double> price { get; set; }
    public Nullable<System.DateTime> date { get; set; }
    public Nullable<bool> access { get; set; }
}

Upvotes: 1

Views: 1363

Answers (1)

laskdjf
laskdjf

Reputation: 1183

To set auto-increment to your database Key you can set the Identity property to your table definition.

[ID]   INT   IDENTITY (1, 1) NOT NULL

Or change the ID attribute to:

[Key]  
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }

Upvotes: 2

Related Questions