Entity Framework Context.Configuration.AutoDetectChangesEnabled update issue?

1.7k Views Asked by At

I have to import about 30 lacks of data from spreadsheet into the MSSQL DB. I used Entity Framework for Insert/ Update records into the database. But the default entity framework configuration was very slow performance. The constraint is, I need to verify the record before inserting into the table. If it existed then it should update with new values else it should insert new record into the database. But it is taking very large amount of time to Insert/Update records into database. I found a solution to speed up this process here.

Context.Configuration.AutoDetectChangesEnabled = false; 

Above setting makes a huge difference in speed.

But the big problems, Records are not updated in table when I set AutoDetectChangesEnabled to false, but inserting is fully functional.

Anyone else seeing this problem? Does anybody help to solve this problem?

1

There are 1 best solutions below

0
On

I have fixed this issue by using the below code. entry.State becoming to Unchanged when AutoDetectChangesEnabled set to false.

public virtual void Update(T entity)
    {
        //DbSet.Attach(entity);
        //context.Entry(entity).State =EntityState.Modified;


        if (entity == null)
        {
            throw new ArgumentException("Cannot add a null entity.");
        }

        var entry = context.Entry<T>(entity);

        if (entry.State == EntityState.Detached)
        {
            var pkey = DbSet.Create().GetType().GetProperty(entity.GetType().Name + "ID").GetValue(entity);

            var set = context.Set<T>();
            T attachedEntity = set.Find(pkey);  // You need to have access to key

            if (attachedEntity != null)
            {
                var attachedEntry = context.Entry(attachedEntity);
                attachedEntry.CurrentValues.SetValues(entity);
            }
            else
            {
                entry.State = EntityState.Modified; // This should attach entity
            }
        }
        else if (entry.State == EntityState.Unchanged)
        {
            entry.State = EntityState.Modified;
        }

    }`