I have to perform bulk insert(around 50-100 rows) into multiple tables( around 30 tables), among them some tables are interrelated with foreign keys. I want to do this by using entity framework(EF). But i want this happened with minimum db hit instead to of calling context.SaveChanges() for each table. Is there any way in EF to perform this? If it so please let me know. Thanks in advance!
Asked
Active
Viewed 571 times
1
-
https://stackoverflow.com/questions/5940225/fastest-way-of-inserting-in-entity-framework – Jan Muncinsky Nov 18 '17 at 15:42
-
Impossible to answer this without seeing the actual case in code. – Gert Arnold Nov 18 '17 at 20:50
-
Here one sample case.. – Gowtham Saba Nov 19 '17 at 04:14
-
Here one sample case.. There are 4 tables [A,B,C ,D] A and B are inter related with FK and C and D are interrelated with FK. I want to insert 100 records into all 4 tables. What is the best way to perform this in EF. – Gowtham Saba Nov 19 '17 at 04:34
-
What makes you think you should call *SaveChanges() for each table*? It's simple. To stay in the same generic terms as you choose to describe your problem: add As, Bs, Cs, and Ds to their respective DbSets and call `SaveChanges` *once*. – Gert Arnold Nov 19 '17 at 19:24
1 Answers
0
Entity Framework
doesn't provide a Bulk
feature.
For every row you want to save, a database round-trip is required.
Disclaimer: I'm the owner of Entity Framework Extensions
This library is not free but allows you to perform a BulkSaveChanges
which work like SaveChanges
but faster:
- Bulk SaveChanges
- Bulk Insert
- Bulk Delete
- Bulk Update
- Bulk Merge
Example
// Easy to use
context.BulkSaveChanges();
// Easy to customize
context.BulkSaveChanges(bulk => bulk.BatchSize = 100);
// Perform Bulk Operations
context.BulkDelete(customers);
context.BulkInsert(customers);
context.BulkUpdate(customers);
// Customize Bulk Operations
context.BulkInsert(customers, options => {
options => options.IncludeGraph = true;
});
context.BulkMerge(customers, options => {
options.ColumnPrimaryKeyExpression =
customer => customer.Code;
});

Jonathan Magnan
- 10,874
- 2
- 38
- 60