I have an ASP.NET application using an entity framework model. In the import procedure, with the code below, I get an exception “Cannot insert a duplicate key” for AccountNum in the call SaveChanges, but when execution stops for an exception, I can query the database for an explicitly duplicated field, and there is no pre-record.
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:
1546 ; . , - 1548 (1547 ). 1548 , 1548 SaveChanges. , SaveChanges 1546, .