我有以下代码:
public void BulkInsert(IEnumerable<T> items)
{
var sbCopy = new SqlBulkCopy(_dataContext.Database.Connection.ConnectionString) { BulkCopyTimeout = 60 * 10 };
var tablename = _dbset.GetTableName();
sbCopy.DestinationTableName = tablename;
foreach (PropertyInfo propertyInfo in items.ElementAt(0).GetType().GetProperties())
{
sbCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(propertyInfo.Name, propertyInfo.Name));
}
sbCopy.WriteToServer(items.AsDataReader());
}
items
列表如下所示:
(注意CustomerType
字段)
此外,数据库确实该字段。
两个之间的映射存在:
但是,在执行.WriteToServer()
时,我收到以下异常
{“给定的ColumnName'CustomerType'与数据源中的任何列都不匹配。”}
答案 0 :(得分:1)
您的CustomerType是数据库中的int,它不在代码中,尝试将其强制转换为int。
答案 1 :(得分:0)
源不包含表示IEnumerable<T> items
..不包含ColumnName CustomerType
... .AsDataReader()
函数可能存在错误。 ..
我更喜欢使用ToDatatable
而不是..
public static class ExtensionHelper
{
public static System.Data.DataTable ToDataTable<T>(this IEnumerable<T> data)
{
var AllProperty = (typeof(T)).GetProperties().ToList();
//var AllInsteadOf = InsteadOfProperty.Split('|').SkipWhile(i => string.IsNullOrEmpty(i));
int propcount = AllProperty.Count();
var table = new System.Data.DataTable();
for (int i = 0; i < propcount; i++)
{
var prop = AllProperty[i];
if (prop.CanRead)
{
//If property type is Nullable<T> or It's a string type or it's a custom class theb
//column allowDBNull will be true
bool allowDBNull = false;
if ((prop.PropertyType.IsNullableType()) || (prop.PropertyType == typeof(String)) || (prop.PropertyType.IsCustomClass()))
{
allowDBNull = true;
}
table.Columns.Add(prop.Name, prop.PropertyType.GetCoreType()).AllowDBNull = allowDBNull;
}
}
object[] values = new object[propcount];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
var prop = AllProperty[i];
if (prop.CanRead)
{
values[i] = prop.GetValue(item, null);
}
}
table.Rows.Add(values);
}
return table;
}
public static bool IsNullableType(this Type Value)
{
return (Value.IsGenericType && Value.GetGenericTypeDefinition() == typeof(Nullable<>));
}
public static bool IsCustomClass(this Type Value)
{
return !Value.Namespace.StartsWith("System");
}
/// <summary>
/// Get underlying core type of a nullable data type
/// </summary>
/// <param name="Value">The value.</param>
/// <returns>A Type object</returns>
public static Type GetCoreType(this Type Value)
{
Type u = Nullable.GetUnderlyingType(Value);
return u ?? Value;
}
}
then
sbCopy.WriteToServer(items.ToDataTable());