Handling duplicate insertion

Posted by Francis on Stack Overflow See other posts from Stack Overflow or by Francis
Published on 2012-11-21T16:57:23Z Indexed on 2012/11/21 16:59 UTC
Read the original article Hit count: 220

Filed under:
|
|

So I've got this piece of code which, logically should work but Entity Framework is behaving unexpectedly.

Here:

foreach (SomeClass someobject in allObjects)
{
    Supplier supplier = new Supplier();

    supplier.primary_key = someobject.id;
    supplier.name = someobject.displayname;

    try
    {
       sm.Add(supplier);
       ro.Created++;
    }
    catch (Exception ex)
    {
       ro.Error++;
    }
}

Here's what I have in sm.Add()

    public Supplier Add(Supplier supplier)
    {
        try
        {
            _ctx.AddToSupplier(supplier);
            _ctx.SaveChanges();
             return supplier;
        }
        catch (Exception ex)
        {
            throw;
        }
    }

I can have records in allObjects that have the same id. My piece of code needs to support this and just move on to the next and try to insert it, which I think should work.

If this happens, an exception is throw, saying that records with dupe PKs cannot be inserted (of course). The exception mentions the value of the PK, for example 1000.

All is well, a new supplier is passed to sm.Add() containing a PK that's never been used before. (1001)

Weirdly though, when doing SaveChanges(), EF will whine about not being able to insert records with dupe PKs. The exception still mentions 1000 even though supplier contains 10001 in primary_key.

I feel this is me not using _ctx properly. Do I need to call something else to sync it ?

© Stack Overflow or respective owner

Related posts about c#

Related posts about LINQ