Search code examples
asp.net-mvccsvautomapperfluent

Fluent Mapping - CsvHelper


I'm using the CsvHelper library built by Josh Close. I thought the datasource where I'll be obtaining the .csv files had a way to mask or 'alias' the column headers with proper naming convention. Unfortunately that's not going to be the case so I'd like to use the Fluent Class Mapping but I'm unclear as to how to implement it.

I built the below class(simplified for this post)

 public class PaymentType
{
    public int PaymentTypeId { get; set; }
    public string BusinessUnit { get; set; }
    public string Region { get; set; }
    public string Status { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public decimal Amount { get; set; }
    public string Name { get; set; }
}

The below method in another class downloads and saves the file

private string DownloadDS(string getURL, string fileName)
    {
        try
        {
            //CSV path
            string url = getURL;

            //Where to save and retrieve CSV file
            string path = AppDomain.CurrentDomain.BaseDirectory + "ImportedFiles\\" + fileName;

            //Download file and save it 
            WebClient client = new WebClient();
            client.DownloadFile(url, path);



            return path;
        }
        catch
        {



            return "";
        }

    }

This method then updates the db

 private void UpdateDB(string path, string fileName)
    {
        try
        {
            //read in file with CsvReader object and output to an enumerable object
            var csv = new CsvReader(new StreamReader(path));
            var importedPaymentTypes = csv.GetRecords<ImportPaymentTypes>();

            //Save each payment type record to the db.  If record exhsists, update it, if not, add it.


           ...

        }
        catch
        {
            ...


        }

    }

I stripped out some of the logging and db logic to shorten the code snippets. I read up on the Fluent Mapping but I'm confused on how to implement it? I understand that I have to build a class, but how do you reference/configure the use of the mapper class?

Here's an example from Josh's site;

http://joshclose.github.io/CsvHelper/#reading-reading-all-records


Solution

  • Take a look at the mapping section. http://joshclose.github.io/CsvHelper/#mapping

    You register the mapping by doing:

    csv.Configuration.RegisterClassMap<PaymentTypeMap>();