将IEnumerable <t>转换为Datatable for SQL批量复制的最佳方法</t>

时间:2013-05-30 16:57:20

标签: c# sql

我有一个模型,以及我需要复制到数据库中的实例列表(大约5000个)。

我正在尝试将我的对象同化为数据表,但我不知道该怎么做:

public class BookingType {

    public int ID { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public int RandomProperty { get; set; }
    public int RandomProperty2 { get; set; }

}

public void InsertSomeStuff(IEnumerable<BookingType> bookings) {
    using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString)) {
        conn.Open();

        DataTable dt = new DataTable();

        using (SqlBulkCopy copy = new SqlBulkCopy(conn)) {
            copy.ColumnMappings.Add(0, 1);

            copy.DestinationTableName = "dbo.Bookings";
            copy.WriteToServer(dt);
        }
    }
}

我该怎么做?

1 个答案:

答案 0 :(得分:5)

你使用linq来sql吗?在这种情况下,这种方法非常可爱:Using SQL bulk copy with your LINQ-to-SQL datacontext

partial class MyDataContext
{
    partial void OnCreated()
    {
        CommandTimeout = 5 * 60;
    }

    public void BulkInsertAll<T>(IEnumerable<T> entities)
    {
        entities = entities.ToArray();

        string cs = Connection.ConnectionString;
        var conn = new SqlConnection(cs);
        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 => GetPropertyValue(
              property.GetValue(entity, null))).ToArray());
        }

        bulkCopy.WriteToServer(table);
        conn.Close();
    }

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

    private object GetPropertyValue(object o)
    {
        if (o == null)
            return DBNull.Value;
        return o;
    }
}