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

fre*_*hie 15 c# linq 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();
}
Run Code Online (Sandbox Code Playgroud)

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

谢谢你的澄清.

And*_*Mao 27

我修改了以下链接中的代码以提高效率并在我的应用程序中使用它.它非常方便,因为您可以将它放在当前自动生成的类之上的部分类中.而不是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<T>(IEnumerable<T> 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;
}
Run Code Online (Sandbox Code Playgroud)

  • 使用 Linqpad 我不得不将 `t.GetProperties().Where(EventTypeFilter)` 改为 `t.GetFields()`。在多一点零一分钟内插入了 20 万行!(y) (2认同)

Sam*_*ron 8

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

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

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

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