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();
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With