Search code examples
c#sqlentity-frameworkforeign-keysprimary-key

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 :

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.