使用linq-to-sql进行批量插入

我有一个看起来像这样的查询:

using (MyDC TheDC = new MyDC()) { foreach (MyObject TheObject in TheListOfMyObjects) { DBTable TheTable = new DBTable(); TheTable.Prop1 = TheObject.Prop1; ..... TheDC.DBTables.InsertOnSubmit(TheTable); } TheDC.SubmitChanges(); } 

此查询基本上使用linq-to-sql将列表插入到数据库中。 现在我在网上看到L2S不支持批量操作。 我的查询是通过一次插入每个元素还是一次写入所有元素来工作的?

谢谢你的澄清。

术语Bulk Insert通常是指基于SQL Server特定的超快速bcp的SqlBulkCopy实现。 它建立在IRowsetFastLoad之上 。

任何情况下,Linq-2-SQL都不使用此机制实现插入。

如果您需要将数据批量加载到SQL Server并且需要快速,我建议使用SqlBulkCopy进行手动编码。

Linq-2-SQL将尝试执行一些优化来加速多个插入,但是它仍然会达不到许多微ORM(即使没有我知道的实现SqlBulkCopy的微ORM)

我修改了以下链接中的代码以提高效率并在我的应用程序中使用它。 它非常方便,因为您可以将它放在当前自动生成的类之上的部分类中。 而不是InsertOnSubmit将实体添加到列表,而不是SubmitChanges调用YourDataContext.BulkInsertAll(list)

http://www.codeproject.com/Tips/297582/Using-bulk-insert-with-your-linq-to-sql-datacontex

 partial void OnCreated() { CommandTimeout = 5 * 60; } public void BulkInsertAll(IEnumerable entities) { using( var conn = new SqlConnection(Connection.ConnectionString)) { conn.Open(); Type t = typeof(T); var tableAttribute = (TableAttribute)t.GetCustomAttributes( typeof(TableAttribute), false).Single(); var bulkCopy = new SqlBulkCopy(conn) { DestinationTableName = tableAttribute.Name }; var properties = t.GetProperties().Where(EventTypeFilter).ToArray(); var table = new DataTable(); foreach (var property in properties) { Type propertyType = property.PropertyType; if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) { propertyType = Nullable.GetUnderlyingType(propertyType); } table.Columns.Add(new DataColumn(property.Name, propertyType)); } foreach (var entity in entities) { table.Rows.Add( properties.Select( property => property.GetValue(entity, null) ?? DBNull.Value ).ToArray()); } bulkCopy.WriteToServer(table); } } private bool EventTypeFilter(System.Reflection.PropertyInfo p) { var attribute = Attribute.GetCustomAttribute(p, typeof(AssociationAttribute)) as AssociationAttribute; if (attribute == null) return true; if (attribute.IsForeignKey == false) return true; return false; } 

它将为每条记录生成一个insert语句,但会在一个批处理中将它们全部发送到服务器并在单个事务中运行。

这就是循环外的SubmitChanges()。

如果你把它移到里面,那么通过循环的每次迭代都会转到INSERT的服务器并在它自己的事务中运行。

我不相信有任何方法可以启动SQL BULK INSERT。