如何在Entity Framework v4中批量插入?

时间:2016-08-02 11:07:55

标签: c# entity-framework-4

我一整天都在寻找解决方案,但在这里找不到任何解决方案,我正在寻求帮助。

我有三张表用于保存组&他们在我的数据库中的联系为简单起见,请将其名称视为table_1,table_2& TABLE_3

table_1(组表)

+----------+------+
| Group_Id | Name |
+----------+------+
|        1 | A    |
|        2 | B    |
|        3 | C    |
+----------+------+

table_2(联系表):

+------------+-------+--------+
| Contact_Id | name  | number |
+------------+-------+--------+
|          1 | Jack  |    123 |
|          2 | Sam   |    456 |
|          3 | Alice |    789 |
+------------+-------+--------+

table_3(连接表)

+-----------------+----------+------------+
| ContactGroup_Id | Group_Id | Contact_Id |
+-----------------+----------+------------+
|               1 |        1 |          1 |
|               2 |        2 |          2 |
|               3 |        2 |          3 |
+-----------------+----------+------------+

现在我正在我的Web应用程序中读取excel文件,然后将批量联系人添加到数据库。使用EF4,这就是我想要做的事情:

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();
   }
}

现在你可以看到我每次都要调用entity.SaveChanges()来自动生成table_2的PK以插入table_3。对数百或数千条记录执行此操作确实会减慢我的应用程序速度,我知道这是一种不好的方法。

还有其他解决方法吗?如果我使用任何第三方批量插入扩展程序执行此操作或在每两百条记录后调用SaveChanges(),那么如何在table_2中插入table_3的自动生成的PK?

1 个答案:

答案 0 :(得分:0)

查看this extension的Entity Framework,它与版本4.x到6.x的EF兼容。

我已经使用了几次,而且效果很好。

修改

通过iserting items within a stored procedure解决PK问题,在一次调用中完成所有插入操作,以避免.NET代码处理插入和SQL Server之间的数千次往返