簡體   English   中英

SQL BulkCopy不插入數據庫

[英]SQL BulkCopy doesn't insert into database

我的大多數應用程序都使用LinqToSQL,但是我需要從文件中上傳文件,從而插入大量數據。

在這里,我有一個數據列表,我正在嘗試插入它。 我轉換為表(從列映射中刪除了Identity 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是可行的,但是這弄亂了其他所有東西。

解決方案:在BulkInsert中使用DataContext.Connection(對SQLConnection的廣播)。 然后它使用已經打開的sql連接,現在看起來工作正常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM