I have been searching for a solution all day but couldn't find any so here I am, looking for some help.
I have three tables for saving groups & their contacts in my database. For simplicity sake, consider their name as table_1, table_2 & table_3
table_1 (Group Table)
+----------+------+
| Group_Id | Name |
+----------+------+
| 1 | A |
| 2 | B |
| 3 | C |
+----------+------+
table_2 (Contact Table):
+------------+-------+--------+
| Contact_Id | name | number |
+------------+-------+--------+
| 1 | Jack | 123 |
| 2 | Sam | 456 |
| 3 | Alice | 789 |
+------------+-------+--------+
table_3 (Junction Table)
+-----------------+----------+------------+
| ContactGroup_Id | Group_Id | Contact_Id |
+-----------------+----------+------------+
| 1 | 1 | 1 |
| 2 | 2 | 2 |
| 3 | 2 | 3 |
+-----------------+----------+------------+
Now I am reading excel file in my web application and then adding bulk contacts to database. Using EF4, this is what I am trying to do :
using (TransactionScope obj = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted, Timeout = TransactionManager.MaximumTimeout }))
{
for (int i = 1; i < totalrows; i++)
{
table_2 objTable_2 = new table_2();
objTable_2.name = "ABC";
objTable_2.number= "999";
entity.table_2.AddObject(objTable_2);
entity.SaveChanges();
table_3 objTable_3 = new table_3();
objTable_3.Group_Id = "1";
objTable_3.Contact_Id = objTable_2.Contact_Id;
entity.table_3.AddObject(objTable_3);
entity.SaveChanges();
}
}
Now as you can see I have to call entity.SaveChanges()
every time to get the auto-generated PK of table_2
to insert in table_3
. Doing this for hundreds or thousands of records is really slowing my application and I know this is a bad way of doing this.
Is there any other work around for this ? if I do this using any third-party bulk-insert extension or calling SaveChanges()
after every couple of hundred records then how do I get auto-generated PK for table_2
to insert in table_3
?
Have a look at this extension for Entity Framework, which is compatible with EF from version 4.x to 6.x.
I've used it a couple of times, and its works pretty well.
Edit:
Solving the PK issue by iserting items within a stored procedure , doing all inserts from it in one call, to avoid thousands of round-trips between .NET code handling inserts and SQL Server
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.