I am using C# console application to read a .CSV file, process it and save the data into a database. While reading the code, I get the correct number of records, but all records are of the last record.
So for example, the file has 50 records and first column of last row is Shane, the record in the below code will have 50 rows but each with the data from Shane row.
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
csv.Configuration.TrimOptions = CsvHelper.Configuration.TrimOptions.Trim;
var obj = new Students();
var records = csv.EnumerateRecords(obj); //Reads correct number of records but its only the last record multiple times.
}
What am I missing?
The problem, as others have commented, is that if you do something to enumerate your records, like calling
records.ToList(), your list is now full of references to the same obj,var obj = new Students();.csv.GetRecords<Student>().ToList()is like having a notebook and writing out each record on each page. And your list looks like:csv.EnumerateRecords(obj).ToList()is like having a single sheet of paper and you use erasable ink or pencil for the actual data. AsCsvReadergives you the records, it takes less time to write them out because you don't have to write outFirstName: Foo,LastName: Bar, you can just erase theFooand theBarand write in the new data. But now your list looks like:And your
var objhas now been overwritten with the last record that was yielded byCsvReader.If you wanted to save each individual record using
EnumerateRecord, you would need to save them as they were being enumerated.Here is another way to see that you are looking at a list of the same object.
Outputs