False Duplicate Key Error in Entity Framework Application
- by ProfK
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)
{
}
}
}