System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YX.Entity;
namespace YX.DAL.Extenstions
{
public static class SqlBulkCopyHelper
{
public static void BulkInsertAll<T>(IEnumerable<T> entities)
{
entities = entities.ToArray();
var cons = new Sam_DBEntities();
string cs = cons.Database.Connection.ConnectionString;
var conn = new SqlConnection(cs);
conn.Open();
Type t = typeof (T);
var bulkCopy = new SqlBulkCopy(conn)
{
DestinationTableName = t.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 ), property.PropertyType.Name)).ToArray());
}
foreach (DataColumn dc in table.Columns)
{
bulkCopy.ColumnMappings.Add( new SqlBulkCopyColumnMapping(dc.ColumnName, dc.ColumnName));
}
bulkCopy.WriteToServer(table);
conn.Close();
}
private static 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 static object GetPropertyValue( object o, string type)
{
if (o == null )
{
return DBNull.Value;
}
return o;
}
}
}
今天使用SqlBulkCopy时,一直报错。
错误信息如下
来自数据源的 String 类型的给定值不能转换为指定目标列的类型 datetime。 ---> System.FormatException: 将参数值从 String 转换到 DateTime 失败。 ---> System.FormatException: 该字符串未被识别为有效的 DateTime。
我就开始检查这个表中的时间字段,结果检查了N次之后,发现所有插入表中的DateTime都是正确的。
后来在尝试其他方法后,发现由于我使用的DataTable中未包含自增长的列,加上自增列之后,就正确插入到数据库中了。
分析了一下,应该是列对应错误,
SqlBulkCopy不是根据表的ColumnName来匹配的,而是根据ColumnIndex匹配。所以插入数据的表需要和数据库中表的列名顺序完全一致
如果需要按照ColumnName对应来插入数据,可以指定SqlBulkCopyColumnMapping。代码如下
SqlBulkCopy sbc = new SqlBulkCopy(conPrivate);
foreach (DataColumn dc in dt.Columns)
sbc.ColumnMappings.Add(new SqlBulkCopyColumnMapping(dc.ColumnName, dc.ColumnName));
EF中使用SqlBulkCopy
标签:ota generic column 错误信息 目标 ble mat format database
查看更多关于EF中使用SqlBulkCopy的详细内容...