CsvHelper is a .NET library for reading and writing CSV files. In a board-game API, it reads a dataset and maps each row to a C# object. That object can then supply values for database entities, without requiring a custom CSV parser. section 5.3.2 section 5.7
To use it for a CSV import:
- Install CsvHelper 30.0.1 through NuGet, the Package Manager console, or the dotnet CLI. section 5.3.2
- Create a C# class with properties for the CSV columns. Use CsvHelper’s [Name] attribute when a header such as “Year Published” cannot be used directly as a property name. Nullable properties allow rows with missing fields to be mapped. section 5.3.3
- Configure the file’s culture, header row, and delimiter; open it with StreamReader; then pass the reader and configuration to CsvReader. GetRecords<BggRecord>() supplies the mapped rows. section 5.3.5
- For each row, skip records without an ID or name and board games already in the database. Create entities from the remaining values, save the changes, and return counts including skipped rows. section 5.3.5
var config = new CsvConfiguration(CultureInfo.GetCultureInfo("pt-BR"))
{
HasHeaderRecord = true,
Delimiter = ";",
};
using var reader = new StreamReader(
System.IO.Path.Combine(_env.ContentRootPath, "Data/bgg_dataset.csv"));
using var csv = new CsvReader(reader, config);
var existingBoardGames = await _context.BoardGames
.ToDictionaryAsync(bg => bg.Id);
var existingDomains = await _context.Domains
.ToDictionaryAsync(d => d.Name);
var existingMechanics = await _context.Mechanics
.ToDictionaryAsync(m => m.Name);
var now = DateTime.Now;
The reader setup specifies the dataset’s semicolon delimiter and header row, opens bgg_dataset.csv from the application’s Data folder, and constructs CsvReader. section 5.3.5
Seeding the board-game database
A PUT action can run the import on demand. CsvHelper maps the dataset’s rows to BggRecord objects; the action turns usable records into BoardGame entities, saves them through EF Core, and reports the resulting counts. Skipping existing IDs makes repeated calls avoid adding those board games again. section 5.3.3 section 5.3.5
