How to add CsvHelper records to DataTable to use for SqlBulkCopy to the database

后端 未结 4 1289
旧时难觅i
旧时难觅i 2021-02-14 08:40

I am trying to read a CSV file with CsvHelper, load each record into a DataTable, and then use SqlBulkCopy to insert the data into a database table. With the current code, I get

4条回答
  •  清酒与你
    2021-02-14 09:11

    I was able to get this to work by adding a DataTable row and filling it in explicitly, instead of trying to add a CsvHelper record as a row.

    I used the following part instead of the similar part that is shown above:

    foreach (var record in records)
    {
        DataRow row = dt.NewRow();
        record.CompanyId = company.Id;
        row["Date"] = record.Date;
        row["Close"] = record.Close;
        row["AdjClose"] = record.AdjClose;
        row["High"] = record.High;
        row["Low"] = record.Low;
        row["Open"] = record.Open;
        row["Volume"] = record.Volume;
        row["CompanyId"] = record.CompanyId;
        dt.Rows.Add(row);
    }
    

    If you can solve the issue without so much hard coding, I will accept your answer as the answer.

提交回复
热议问题