Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to do bulk insert/update with Entity Framework

I have a list of entities and I want to insert them into a database. If the entity already exists in the database as is then it needs to be skipped. If its in the database but with different values then it needs to be updated.

Is there any way to do this other than do a db call per item?

My plan is to try an insert, if a unique constraint exception on the key is thrown then do an update.

like image 736
Ian Warburton Avatar asked Jun 24 '13 11:06

Ian Warburton


People also ask

Does EF core support bulk insert?

The EF Bulk Insert feature let you insert thousands of entities in your database efficiently. This feature is provided by the library EF Extensions (Included with EF Classic). EF Extensions is used by over 2000 customers all over the world and supports all Entity Framework versions (EF4, EF5, EF6, EF Core, EF Classic).

How do I insert multiple rows in Entity Framework?

You can add multiple records or multiple objects using the AddRange method of DbSet as shown in the following code. The code creates a list of department objects and inserts two new departments to the list. We add the list to the context using the AddRange method.


2 Answers

Just don't use Entity Framework in this case. Just use a stored procedure (how to depends on the version/approach you use with EF, you might will have to extend your DbContext or add a mapping from the entity model).

If you're using SQL Server, then in your store procedure, do use the MERGE command that efficiently does exactly what you need: insert if it doesn't exist, or update if it does. Everything in a single, efficient SQL query.

like image 119
ken2k Avatar answered Nov 03 '22 00:11

ken2k


EF isnt suited to BULK inserts. For 1000s of records it ok, but large numbers (100k plus) its slow.

If you are planning to use EF.

  • try AddOrUpdate method , (instead of insert/Update)
  • Disable tracking,
  • commit every 1000 records or fewer.

eg

Context.Set<TPoco>().AddOrUpdate(poco); //... Context.Configuration.AutoDetectChangesEnabled = //.. Context.SaveChanges(); 

If copying unrelated data you can try those tables in parallel (doh)

like image 31
phil soady Avatar answered Nov 02 '22 23:11

phil soady