首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SQL BulkCopy不插入数据库

SQL BulkCopy不插入数据库
EN

Stack Overflow用户
提问于 2014-07-22 18:16:34
回答 1查看 715关注 0票数 0

我的大多数应用程序都使用LinqToSQL,但是我需要从文件中进行一些上传,从而插入大量数据。

这里我有一个数据列表,我正在尝试插入它。我将转换为表(从列映射中省略了identity MeterDataId字段)。一切看起来都很好,但是数据没有被提交。没有任何例外的报告。

我检查了表,它确实有这三个字段的数据。

我应该以某种方式设置ID字段吗?

谢谢

代码语言:javascript
复制
        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();
EN

回答 1

Stack Overflow用户

发布于 2014-07-22 19:02:15

代码语言:javascript
复制
   string cs = DataContext.Connection.ConnectionString;

更新了连接字符串,现在似乎正在工作!

编辑,,这不是诀窍。我发现处理Linq DataContext是有效的,但这却把其他一切都搞砸了。

解决方案:将DataContext.Connection (强制转换为SQLConnection)与BulkInsert一起使用。然后,它使用已经打开的sql连接,现在似乎运行良好。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24894795

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档