Entity Framework update/insert multiple entities
For EFCore you can use this library:
https://github.com/borisdj/EFCore.BulkExtensions
Note: I'm the author of this one.
And for EF 6 this one:
https://github.com/TomaszMierzejowski/EntityFramework.BulkExtensions
Both are extending DbContext
with Bulk operations and have the same syntax call:
context.BulkInsert(entitiesList);
context.BulkUpdate(entitiesList);
context.BulkDelete(entitiesList);
EFCore version have additionally BulkInsertOrUpdate
method.
- Assuming that the classes in apiData are the same as your entities, you should be able to use
Attach(newAccount, originalAccount)
to update an existing entity. For bulk inserts I use
AddRange(listOfNewEntitities)
. If you have a lot of entities to insert it is advisable to batch them. Also you may want to dispose and recreate theDbContext
on each batch so that it's not using too much memory.var accounts = new List<Account>(); var context = new YourDbContext(); context.Configuration.AutoDetectChangesEnabled = false; foreach (var account in apiData) { accounts.Add(account); if (accounts.Count % 1000 == 0) // Play with this number to see what works best { context.Set<Account>().AddRange(accounts); accounts = new List<Account>(); context.ChangeTracker.DetectChanges(); context.SaveChanges(); context?.Dispose(); context = new YourDbContext(); } } context.Set<Account>().AddRange(accounts); context.ChangeTracker.DetectChanges(); context.SaveChanges(); context?.Dispose();
For bulk updates, there's not anything built in in LINQ to SQL. There are however libraries and solutions to address this. See e.g. Here for a solution using expression trees.