1

我有一个模型和一个需要复制到数据库中的实例列表(大约 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);
        }
    }
}

我该怎么做呢?

4

1 回答 1

5

你在使用 linq to 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;
    }
}
于 2013-05-30T17:08:04.787 回答