I'm building an Entity Framework Core web project using code first migrations and when I update the data via update method, I get the following error message:
Violation of PRIMARY KEY constraint 'PK_ApplicationUserLanguages'. Cannot insert duplicate key in object 'dbo.ApplicationUserLanguages'. The duplicate key value is (29, a7314beb-fcbc-4e28-b331-6e2f5d3c44e8).
Here are my data structure:
public class Languages
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public Guid? UserId { get; set; }
[JsonIgnore]
public virtual List<ApplicationUser>? Users { get; set; }
}
public class ApplicationUser : IdentityUser
{
public List<Languages>? Languages { get; set; }
}
Here's my DbContext:
public DbSet<Languages> Languages { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Languages>().HasMany(l => l.Users).WithMany(u => u.Languages);
modelBuilder.Entity<Languages>().HasData(
new Languages { Id = 1, Name = "English" },
new Languages { Id = 2, Name = "Spanish" },
new Languages { Id = 3, Name = "French" },
new Languages { Id = 4, Name = "German" },
new Languages { Id = 5, Name = "Italian" },
new Languages { Id = 6, Name = "Portuguese" },
new Languages { Id = 7, Name = "Dutch" },
new Languages { Id = 8, Name = "Russian" },
new Languages { Id = 9, Name = "Chinese" },
new Languages { Id = 10, Name = "Japanese" },
new Languages { Id = 11, Name = "Korean" },
new Languages { Id = 12, Name = "Arabic" },
new Languages { Id = 13, Name = "Hindi" },
new Languages { Id = 14, Name = "Bengali" },
new Languages { Id = 15, Name = "Urdu" },
new Languages { Id = 16, Name = "Punjabi" },
new Languages { Id = 17, Name = "Telugu" },
new Languages { Id = 18, Name = "Marathi" },
new Languages { Id = 19, Name = "Tamil" },
new Languages { Id = 20, Name = "Gujarati" },
new Languages { Id = 21, Name = "Kannada" },
new Languages { Id = 22, Name = "Odia" },
new Languages { Id = 23, Name = "Malayalam" },
new Languages { Id = 24, Name = "Sindhi" },
new Languages { Id = 25, Name = "Assamese" },
new Languages { Id = 26, Name = "Nepali" },
new Languages { Id = 27, Name = "Sanskrit" },
new Languages { Id = 28, Name = "Sindhi" });
}
Here's my code to update the database:
var user = await _context.Users.FirstOrDefaultAsync(u => u.Id == updateProfile.Id);
if (user != null)
{
user.Languages = updateProfile.Languages;
_context.Entry(user).State = EntityState.Modified;
await _context.SaveChangesAsync();
}
I tried to execute code to delete the languages first then re add them but I keep getting the error. I'm not sure what I'm missing because I'm expecting Entity Framework Core to manage the foreign keys