False Duplicate Key Error in Entity Framework Application

Posted by ProfK on Stack Overflow See other posts from Stack Overflow or by ProfK
Published on 2010-06-07T17:04:31Z Indexed on 2010/06/07 17:32 UTC
Read the original article Hit count: 522

Filed under:
|

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)
                {
                }
            }
        }

© Stack Overflow or respective owner

Related posts about .NET

Related posts about entity-framework