How to bulk insert an object with dynamic length and no column names

时间:2019-01-16 15:20:36

标签: c# sql-server bulk

I consume survey data (delivered as json) from our provider via SSE and deserialize them into an Object. The object holds the following data without the header information, just the data ("1","1","Yes, I do")

|UserNumber  | Variable1   | Variable2    |
|------------|-------------|--------------|
| 1          |      1      |  Yes, I do   |
| 1          |      5      |  No, I do not|

The number of Users and the number of variables differ from survey to survey but at the moment the maximum is 500.000 and 350. The object looks as follows:

(1) User1
  (1) "4482359"
  (2) "12526"
  (3) "5"
  (4) ""
...    
(2) User1
  (1) "5847895"
  (2) "33568"
  (3) "6"
  (4) "2"
...

I store the data in an object,现在我想将数据存储在SQL表中,但是我不确定如何这样做是因为我的对象的长度(两个维度)都不同。我已经完成的就是将数据导入.csv并使用大容量插入(即使由于“,”分隔符而出现问题)

private MyObject abc()

但是为此,我必须遍历所有元素。

我还阅读了有关SQLBulkCopy的信息,但为此我必须将数据带入Datatable并将其与SQL Table映射。但是由于我在对象中没有列名,因此我看不到如何使用它。谁能给我一个有关如何将对象插入数据库的片段?

1 个答案:

答案 0 :(得分:0)

创建一个这样的表

            DataTable dt = new DataTable();
            dt.Columns.Add("UserNumber", typeof(int));
            for(int i = 1; i <=10; i++)
            {
                dt.Columns.Add("Column" + i.ToString(), typeof(string));
            }