Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
841 views
in Technique[技术] by (71.8m points)

c# - I want to import data from CSV file to SQL database using Entity Framework

I want insert data from CSV file to SQL table. Here is my code I don't know how to go further

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

foreach (var row in csvfilerecord)
{
  if (!string.IsNullOrEmpty(row))
  {
    foreach (var cell in row.Split(','))
    {
      var cards = new Cards
      {
        //What to do here to assign data to each column 
      };
    }
  }
}

here is my csv file data

12345,cvv,18-april,name,country,address,state,city,dob,zipcode,phone,email,10
12345,cvv,18-april,name,country,address,state,city,dob,zipcode,phone,email,10

class Definition

        public string nummber { get; set; }
    public string cvv { get; set; }
    public string expDate { get; set; }
    public string name { get; set; }
    public string country { get; set; }
    public string address { get; set; }
    public string state { get; set; }
    public string dob { get; set; }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...