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

asp.net-core c# entity-framework entity-framework-core

Question

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

1
3
5/7/2019 4:52:58 AM

Accepted Answer

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();
5
5/7/2019 5:05:30 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow