2
votes

I have a little program that fetches data from a web service. The program takes the JSON response, maps it to POCOs and writes the objects to a CSV file (automapping). It works perfectly when I ask for "all" the data in the dataset, however, if I query the resource (via OData) like this: "$select EmpNo, FirstName, LastName", the CSV writer will still write all of the columns to the CSV header, e.g. "EmpNo, FirstName, LastName, Street, Address, City, Age" etc. and just insert 0 (if int), false(if boolean) or "" (if string) to the columns that have no data.

The web service correctly returns only the specified columns, so that's not the issue. I use CsvHelper for the object mapping and CSV-writing. (But I'm open to using anything that can solve my problem)

I'd like to only write "EmpNo, FirstName, LastName" and the columns' data to the CSV-file, if that's what I ask for in the OData query.

Any good ideas for solving this?

2
Can you post some of your code? - adaam

2 Answers

3
votes

It is hard to tell without knowing the exact code you're using. But my guess is that when you write your list of objects you're using the model that has the extra fields in it, which are all empty because you didn't request them via odata.

If you want just the subset with CsvHelper, you probably want to specify a CsvClassMap<T> and that will map your existing model into just the fields you want

There are lots of examples on a CsvClassMap here: http://joshclose.github.io/CsvHelper/

The write method will likely have a method overload that will take a classmap.

0
votes

You can create a ClassMapper and specify which properties from the object you want to write (and how you want to write them!)
https://joshclose.github.io/CsvHelper/examples/configuration/class-maps/mapping-properties

Then when you go to write, just specify the ClassMapper

using (var writer = new StreamWriter("path\\to\\file.csv"))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
    csv.Configuration.RegisterClassMap<NameOfClassMapper>();
    csv.WriteRecords(records);
}