SqlBulkCopy和EF - 错误:“给定的ColumnMapping与源或目标中的任何列都不匹配”

时间:2017-02-11 23:47:15

标签: c# sql entity-framework sqlbulkcopy

我已尝试过相关问题中的所有内容,但我仍然遇到此错误。

这是我的实体类:

public class Activity
{
    public bool Active { get; set; }
    public int ActivityId { get; set; }
    public string ItemType { get; set; }
    public double Value { get; set; }
    public int Minute { get; set; }
    public string ItemId { get; set; }
    public DateTime Time { get; set; }
    public DateTime JoinDate { get; set; }
    public DateTime UpdateDate { get; set; }
    public int LectureId { get; set; }
    public virtual Lecture Lecture { get; set; }
}

这是负责执行SqlBulkCopy的存储库方法的内容:

var sqlConnectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
        using (SqlBulkCopy sbCopy = new SqlBulkCopy(sqlConnectionString, SqlBulkCopyOptions.KeepIdentity))
        {
            sbCopy.DestinationTableName = "Activity";
            var table = objs.ToDataTable();
            sbCopy.ColumnMappings.Clear();
            foreach (DataColumn col in table.Columns)
                sbCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(col.ColumnName.Trim(), col.ColumnName.Trim()));       

            using (var connection = new SqlConnection(sqlConnectionString))
            {
                await connection.OpenAsync();
                sbCopy.BatchSize = 48;;

                await sbCopy.WriteToServerAsync(table);
                connection.Close();
            }
        }

最后,ToDataTable代码:

public static DataTable ToDataTable<T>(this IEnumerable<T> collection)
    {
        PropertyDescriptorCollection properties =
            TypeDescriptor.GetProperties(typeof(T));
        DataTable table = new DataTable();

        table.CaseSensitive = true;

        foreach (PropertyDescriptor prop in properties)
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);

        foreach (T item in collection)
        {
            DataRow row = table.NewRow();
            foreach (PropertyDescriptor prop in properties)
                row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;

            table.Rows.Add(row);
        }
        return table;
    }

我需要保存数千行,EF非常慢。任何sugestions?

0 个答案:

没有答案