Inserting CSV data using Entity Framework?

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

Question

It is necessary to use a web app to insert a CSV file with a header into a database.

Is it feasible to use Entity Framework to deliver the data to a stored procedure? Or what is a more effective fix?

The web app must be used, and the table contains an additional column that is merely a unique identifier for each entry.

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 must be aware of which CSV column corresponds to which attribute. You may map values to properties using this data.

Assuming you have an index dictionarycolumnMap You may utilise

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

Please take note that I do not loop over the individual data from a single CSV row.

Also keep in mind that a good CSV parser is required to perform the appropriate escaping and quoting for values that include 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