Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Core: Violation of PRIMARY KEY constraint Cannot insert duplicate key in object

I am getting the following error when inserting records into a child table, Why is Entity Framework Core trying to insert a record into the parent table(IdentityUser table) when I am asking it to insert a record into a child table(Keywords table)?

StackTrace:

An unhandled exception occurred while processing the request.
SqlException: Violation of PRIMARY KEY constraint 'PK_IdentityUser'. Cannot insert duplicate key in object 'dbo.IdentityUser'. The duplicate key value is (39b72c3a-b5bf-43e4-84f9-5cddbe79f6e3).
The statement has been terminated.

Model:

public class Keyword
  {
    public Keyword() { }
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int KeywordId { get; set; }
    public IdentityUser User { get; set; }
    public string Value { get; set; }
    [Timestamp]
    public byte[] RowVersion { get; set; }
  }

Code to save records to Keywords table:

    var keywords = new List<Keyword>();
var identityUser = await UserManager.GetUserAsync(User);
              foreach (var keywordString in keywordsThatNeedToBeSaved)
              {
                keywords.Add(new Keyword()
                {
                  User = identityUser,
                  Value = keywordString
                });
              }
              ScrubberDbContext.Keywords.AddRange(keywords);
                await ScrubberDbContext.SaveChangesAsync();

enter image description here enter image description here enter image description here

like image 450
Ajit Goel Avatar asked May 07 '19 04:05

Ajit Goel


1 Answers

Change keyword class to :

public class Keyword
    {
        public Keyword() { }
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int KeywordId { get; set; }
        public int? UserId { get; set; }
        [ForeignKey("UserId")]
        public IdentityUser User { get; set; }
        public string Value { get; set; }
        [Timestamp]
        public byte[] RowVersion { get; set; }
    }

and change save record to :

var keywords = new List<Keyword>();
 var identityUser = await UserManager.GetUserAsync(User);
              foreach (var keywordString in keywordsThatNeedToBeSaved)
              {
                keywords.Add(new Keyword()
                {
                  UserId = identityUser.Id,
                  Value = keywordString
                });
              }
              ScrubberDbContext.Keywords.AddRange(keywords);
                await ScrubberDbContext.SaveChangesAsync();
like image 156
vahid tajari Avatar answered Nov 07 '22 19:11

vahid tajari