I have an ASP.NET application using an entity framework model. In an import routine, with the code below, I get a “Cannot insert duplicate key” exception for AccountNum on the SaveChanges call, but when execution stops for the exception, I can query the database for the apparently duplicated field, and no prior record exists.
using (var ents = new PvmmsEntities())
{
foreach (DataRow row in importedResources.Rows)
{
var empCode = row["EmployeeCode"].ToString();
try
{
var resource = ents.ActivationResources.FirstOrDefault(rs => rs.EmployeeCode == empCode);
if (resource == null)
{
resource = new ActivationResources();
resource.EmployeeCode = empCode;
ents.AddToActivationResources(resource);
}
resource.AccountNum = row["AccountNum"].ToString();
ents.SaveChanges(true);
} catch(Exception ex)
{
}
}
}
UPDATE:
With employee 1546 I catch a valid duplicate key exception; he has a duplicate bank account. Then, the very next employee is 1548 (1547 is genuinely missing). 1548 has a unique bank account, but for 1548 I get the duplicate key exception on SaveChanges. A profile shows that SaveChanges is still trying to insert 1546, which in fact does still have a duplicate bank account.
Your original object (the one with the “real” duplicate error) is still in the context. Doing
SaveChangesafter adding the “good” object later on tries to save both objects. You must remove the “bad” object you added to the context or new up a new context without the “bad” object added.