Seeding data from csv file
I have a model like this:
I try to seeding data from my csv file like this:
When I run the program, I got the error:
public class Record
{
public int Id { get; set; }
public long caller_id { get; set; }
public long recipient { get; set; }
public DateTime call_date { get; set; }
public DateTime endtime { get; set; }
public int duration { get; set; }
public double cost { get; set; }
public string reference { get; set; }
public string currency { get; set; }
} public class Record
{
public int Id { get; set; }
public long caller_id { get; set; }
public long recipient { get; set; }
public DateTime call_date { get; set; }
public DateTime endtime { get; set; }
public int duration { get; set; }
public double cost { get; set; }
public string reference { get; set; }
public string currency { get; set; }
}I try to seeding data from my csv file like this:
public void SeedDataContext()
{
if (!_ctx.Record.Any())
{
var filePath = "C:/techtest_cdr.csv";
var csvData = System.IO.File.ReadAllLines(filePath).Skip(1);
var datas = new List<Record>();
foreach (var line in csvData)
{
var values = line.Split(',');
var record = new Record
{
caller_id = long.Parse(values[0]),
recipient = long.Parse(values[1]),
call_date = DateTime.ParseExact(values[2], "dd/MM/yyyy",CultureInfo.InvariantCulture),
endtime = DateTime.ParseExact(values[3], "HH/mm/ss", CultureInfo.InvariantCulture),
duration = int.Parse(values[4]),
cost = double.Parse(values[5]),
reference = values[6],
currency = values[7].ToUpper()
};
datas.Add(record);
}
_ctx.Record.AddRange(datas);
_ctx.SaveChanges();
}
} public void SeedDataContext()
{
if (!_ctx.Record.Any())
{
var filePath = "C:/techtest_cdr.csv";
var csvData = System.IO.File.ReadAllLines(filePath).Skip(1);
var datas = new List<Record>();
foreach (var line in csvData)
{
var values = line.Split(',');
var record = new Record
{
caller_id = long.Parse(values[0]),
recipient = long.Parse(values[1]),
call_date = DateTime.ParseExact(values[2], "dd/MM/yyyy",CultureInfo.InvariantCulture),
endtime = DateTime.ParseExact(values[3], "HH/mm/ss", CultureInfo.InvariantCulture),
duration = int.Parse(values[4]),
cost = double.Parse(values[5]),
reference = values[6],
currency = values[7].ToUpper()
};
datas.Add(record);
}
_ctx.Record.AddRange(datas);
_ctx.SaveChanges();
}
}When I run the program, I got the error:
Unhandled exception. System.FormatException: String '' was not recognized as a valid DateTime.Unhandled exception. System.FormatException: String '' was not recognized as a valid DateTime. The format for date time for call_datecall_date in my csv file is dd/mm/yyyy. The format for endtimeendtime in my csv file is HH/mm/ss.