Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error Violation of PRIMARY KEY constraint – C#

I have a problem with inserting data into a list. The error tells me that the Editor class cannot contain 2 identical Ids. I understand the error, but I’m not touching that class, just adding an object to the Books list. Here are my relations :

public class Author
{
    [Key]
    public int AuthorID { get; set; }

    public virtual Editor Editor { get; set; }

    public virtual ICollection<Book> Books { get; set; }
}

public class Book
{
    [Key]
    public int BookID { get; set; }

    [ForeignKey("Author")]
    public int AuthorID { get; set; }

    public virtual Author Author { get; set; }
}

public class Editor
{
    [Key, ForeignKey("Author")]
    public int AuthorID { get; set; }

    public virtual Author Author { get; set; }
}

Here is my addition :

Author Author = DBContext.Authors.FirstOrDefault(a => a.AuthorID == AuthorID);

Book Book = new Book
{
};

Author.Books.Add(Book);

DBContext.SaveChanges();

Here is the error :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SqlException: Violation of PRIMARY KEY constraint ‘PK_dbo.Editor’. Cannot insert duplicate key in object ‘dbo.Editor’. The duplicate key value is (89).

For reasons, I modified the classes but it is the same relations.
Thank you!

I tried rebuilding the tables and changing the relationships. However, when I changed Editor’s relationship, instead of giving me an error, it was creating empty Books from it, the last one was linked to the Author and the other ones were delinked.

>Solution :

Try following class structure

public class Author
{
    [Key]
    public int AuthorID { get; set; }

    public virtual Editor Editor { get; set; }

    public virtual ICollection<Book> Books { get; set; }
}

public class Book
{
    [Key]
    public int BookID { get; set; }

    [ForeignKey("Author")]
    public int AuthorID { get; set; }

    public virtual Author Author { get; set; }
}

public class Editor
{
    [Key]
    public int EditorID { get; set; }

    [ForeignKey("Author")]
    public int AuthorID { get; set; }

    public virtual Author Author { get; set; }
}

I believe Key (Ids) are Autogenerated.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading