SQL BulkCopy不能插入数据库
本文关键字:数据库 插入 不能 BulkCopy SQL | 更新日期: 2023-09-27 18:14:18
我的大部分应用程序都使用LinqToSQL,但我需要从文件中做一些上传,从而插入大量的数据。
这里我有一个数据列表,我正在尝试插入它。我将其转换为表(从列映射中去掉标识MeterDataId字段)。一切似乎都很好,但数据没有提交。没有异常报告。
我检查了表,它确实有三个字段的数据。
我应该设置ID字段吗?
感谢 SqlConnection SqlConnection = null;
try {
string cons = "Data Source=(LocalDB)''v11.0;AttachDbFilename='"D:''Visual Studio Projects''SEMS''SEMS''bin''Debug''DataCore.mdf'";Integrated Security=True";
SqlConnection = new SqlConnection(cons);
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
Type t = typeof(MeterData);
var tableAttribute = (TableAttribute)t.GetCustomAttributes(
typeof(TableAttribute), false).Single();
var bulkCopy = new SqlBulkCopy(SqlConnection) {
DestinationTableName = tableAttribute.Name
};
List<PropertyInfo> properties = new List<PropertyInfo>();
properties.Add(t.GetProperty("DateTime"));
properties.Add(t.GetProperty("Value"));
properties.Add(t.GetProperty("Difference"));
var table = new DataTable();
foreach (var property in properties) {
Type propertyType = property.PropertyType;
if (propertyType.IsGenericType &&
propertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) {
propertyType = Nullable.GetUnderlyingType(propertyType);
}
// set the SqlBulkCopy column mappings.
table.Columns.Add(new DataColumn(property.Name, propertyType));
var clrPropertyName = property.Name;
var tableColumnName = property.Name;
bulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(clrPropertyName, tableColumnName));
}
// Add all our entities to our data table
foreach (var entity in insertMeterDatas) {
var e = entity;
table.Rows.Add(properties.Select(property => GetPropertyValue(property.GetValue(e, null))).ToArray());
}
bulkCopy.WriteToServer(table);
SqlConnection.Close();
string cs = DataContext.Connection.ConnectionString;
更新了连接字符串,现在似乎可以工作了!
编辑这不是诀窍。我发现处理Linq DataContext是有效的,但这把其他一切都搞砸了。
解决方法:使用DataContext。与BulkInsert的连接(转换为SQLConnection)。然后它使用已经打开的sql连接,现在似乎工作良好。