【发布时间】:2014-07-22 18:16:34
【问题描述】:
我的大部分应用程序都使用 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();
【问题讨论】:
-
你应该用
using打开sql连接,然后你就不需要清理连接了。它将自动完成。此外,如果出现故障,连接将不会按照您现在编写代码的方式正确关闭。看看它,using很棒!
标签: c# sql sql-server bulkinsert