c# - 使用 linq-to-sql 批量插入

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

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

感谢您的澄清。

最佳答案

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

关于c# - 使用 linq-to-sql 批量插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9220901/

相关文章:

c# - 如何生成通过 FileStream 写入的数据已在磁盘上的通知?

c# - 如何有效地将数百万条记录从 .NET 流式传输到 SQL Server

c# - 无法从代码更改 SiteCore 8.0(更新 3)中的 mvc 布局

c# - 使用迭代方法和 LINQ 查找模型的最常见属性

c# - 在集合中查找循环项(非传递项)

c# - 自动将 LinqToSql 基类添加到实体的方法?

.net - 如何在动态 linq 查询中使用 "contains"或 "like"?

c# - HTTPS 代理实现 (SSLStream)

c# - 使用 linq 在数组列表中找到最接近的值?

c# - LINQ to SQL : Advanced queries against lists, 数组和对象列表