EF6 : AddRange throws exception

c# entity-framework-6

Question

I am trying to use AddRange method to create a bulk insert into my DB.

This is what I do :

    public virtual IEnumerable<E> InsertRange(IEnumerable<E> entities)
    {
        Context.Set<E>().AddRange(entities);

        if (isAutoSave)
            Context.SaveChanges();
    }

When I call SaveChanges() I get an exception saying:

Conflicting changes detected. This may happen when trying to insert multiple entities with the same key.

I think the problem might be in my model. My Id column, which is a PK and Identity is of type int, which cause all the new entities to be with Id=0. What can I do to solve that?

Thanks, Matan

1
0
1/24/2016 5:32:15 PM

Popular Answer

Maybe you can try to disable ef tracking - do whatever you need, save changes and enable it back. That will also increase performance of your insert operation.

So, before calling method which will insert and save changes just add this:

context.Configuration.AutoDetectChangesEnabled = false;

And when you are done enable it back:

context.Configuration.AutoDetectChangesEnabled = true;

I hope this will help you.

0
1/24/2016 7:36:13 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow