SQL BulkCopy不会插入数据库

时间:2014-07-22 18:16:35

标签: c# sql sql-server bulkinsert

我的大多数应用程序都使用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();

1 个答案:

答案 0 :(得分:0)

   string cs = DataContext.Connection.ConnectionString;

更新了连接字符串,似乎现在正在运行!

编辑这不是诀窍。我找到了处理它工作的Linq DataContext,但这搞砸了其他一切。

解决方案:使用BulkInsert的DataContext.Connection(Cast to SQLConnection)。然后它使用已经打开的sql连接,现在看起来工作正常。

相关问题