0

Having issues with Save not working and looking for most efficient methodology.

If I do this inside the loop it works, but is super slow:

var entity = dbContext.customer.find(fubar.id);
dbContext.Entry(entity).CurrentValues.SetValues(fubar);

Here is the code

var myCollection = dbContext.customer.where(...);

foreach (var fubar in myCollection.where(x => x.addressId == null))
{
   var existingRecord = dbContaxt.address.where(...);
   fubar.addressId = existingRecord.id;
   dbContext.table.Add(fubar);
}

dbContext.SaveChanges();

First issue, my changes are not being saved and I am not sure why.

Second issue, is there a more efficient way to do this? The collection can have thousands of records in it.

Would something like Parallel.ForEach() be appropriate here?

Thanks, Sammer

Sammer
  • 145
  • 2
  • 11
  • Refer https://stackoverflow.com/questions/44194877/how-to-bulk-update-records-in-entity-framework it should fix both the issues – Mohammed Dawood Ansari Aug 13 '19 at 18:59
  • Thank you Mohammed, getting rid of the dbContext.table.add(fubar) fixed the save issue. And getting all the address records into a List and selecting from that List was as much performance increase as I could get, since potentially every record needs a different update. – Sammer Aug 13 '19 at 19:51
  • Yes, always remember the thumb rule, you only use table.Add when you want to insert the new record, if you want to update just set the new value and savechanges(), additionally I think you can have a look on change tracking and AsNoTracking, and then using Entity.State Modified with AsNoTracking, learning this very improve your query performance significantly – Mohammed Dawood Ansari Aug 13 '19 at 20:10

1 Answers1

0

Whenever you are reading the entities read them as Queryable()

For Example: var myCollection = dbContext.customer.AsQueryable().where(...);

So that you are querying on that table without getting all the records. But if you dont use it this will get all the records and then apply where condition on it.

Just see the difference by applying it to a query with more number of records.

DEV
  • 949
  • 1
  • 9
  • 29
  • this is not true. DbSet implements IQueryable. The .AsQueryable() call does have an additional cast, but the execution of either query only happens when the result is enumerated. – DevilSuichiro Aug 13 '19 at 20:32