I am trying to update my table Bareme but I get an exception about my unique key (Categorie , Section), but as seen here am updating only my salary if the object does exist, and I’ve verified by “DEBUG” that none of the inserted objects is duplicated
The inner exception says :
Violation of UNIQUE KEY constraint ‘IX_Bareme’. Cannot insert duplicate key in object ‘dbo.Bareme’.\r\nThe statement has been
terminated.
Code:
for (int i = 1; i <= sl_cat.Value; i++)
for (int j = 1; j <= sl_sec.Value; j++)
{
Bareme brm = db.Entities.Baremes.Select(X => X).Where(X => X.Section == j && X.Categorie == i).FirstOrDefault();
if (brm != null)
db.Entities.Baremes.DeleteObject(brm);
brm = new Bareme();
brm.Categorie = i;
brm.Section = j;
brm.Salaire = dt.Rows[j - 1][i.ToString()].ToString().ToDecimal();
db.Entities.Baremes.AddObject(brm);
}
try
{
db.Entities.SaveChanges();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Please use the
SaveChanges MethodwithSaveOptionsforDetectChangesBeforeSaveExample