Inserting CSV data using Entity Framework?

c# entity-framework entity-framework-6 sql-server

Question

There is a CSV file with a header that needs to be inserted into a database through a web app.

Is it possible to send the data to a stored procedure via Entity Framework? Or what is a better solution?

It has to be done through the web app and the table has an extra column which is just a unique id for each row.

1
0
7/6/2018 8:34:37 PM

Accepted Answer

var readcsv = File.ReadAllText(filepath);
string[] csvfilerecord = readcsv.Split('\n');

foreach (var row in csvfilerecord)
{
  if (!string.IsNullOrEmpty(row))
  {
    var cells = row.Split(','))
    var card = new Cards
      {
         number = cells[0], // number is in first cell
         cvv = cells[1],   // cvv is in second cell
         // ...
      };
  }
}
0
6/29/2016 10:08:47 AM

Popular Answer

You need to know which column of the CSV maps to which property. With this information you can map values into properties.

Assuming you have a dictionary of indexes columnMap you can use

var cells = row.Split(',');
var cards = new Cards {
  prop = cells[columnMap["prop"]],
  nextProp = cells[columnMap["nextProp"]],
  …
}

Note I do not iterate over the separate values from one row in the CSV.

Also note you need a proper CSV parser to handle the escaping/quoting necessary for when values contain commas or quotes.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow