简体   繁体   中英

EF6 : AddRange throws exception

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM