views:

110

answers:

1

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.

A: 

Your original object (the one with the "real" duplicate error) is still in the context. Doing SaveChanges after 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.

Craig Stuntz
@Craig, I'm having trouble using TryGetObjectByKey with a property that isn't the actual entity key, i.e. resource.ResourceId. I don't have an ID value because the code doesn't find an existing record.
ProfK
You need to look at the object's `EntityKey` property.
Craig Stuntz
TryGetObjectByKey succeeds, but I assume that's because I have already added the object to the entity set. I add it as soon as I instantiate it.
ProfK
Hmmm... I'm changing my guess, then. The duplicate record may have been added in a transaction not yet visible to SSMS. Try capturing the INSERT with profiler and executing it directly.
Craig Stuntz
Aha. The exception I get is straight after a valid exception, which I have hitherto ignored. When I get my 'invalid' exception, the context is still trying to persist the same data as caused the valid exception, not my new, unique data. Updated question to reflect this better.
ProfK
OK. I'll update my answer.
Craig Stuntz
Thanks yes, I just figured that. I now delete the object in the catch, if it was added.
ProfK