Is it possible to write an empty CSV column when a nested object is null, within the object passed into CsvWriter.WriteRecords()?
If I try to write an object using the CsvWriter.WriteRecords(), and one of the values in the object is an object itself and that object is null nothing will be written in the column for that object.
Here is an example :
public class AddressObject {
public string City { get; set; }
public string Road { get; set; }
public int RoadNumber { get; set; }
}
public class LocationRow {
public Guid RowId { get; set; }
public AddressObject Address { get; set; }
public double? Latitude { get; set; }
public double? Longitude { get; set; }
}
So when I try to call CsvWriter.WriteRecords() for LocationRow and the AddressObject is null, a column won't be written for that object:
b9aefb12-feef-47da-cb37-08d6bef08536,-37,175,
But I would expect it to look like:
b9aefb12-feef-47da-cb37-08d6bef08536,,-37,175
.
But if latitude or longitude is null, it will put an empty string in that column which is what I would expect:
b9aefb12-feef-47da-cb37-08d6bef08536,5 Bader St Hamilton,,
I am using my own custom converter for the 'AddressObject' class, but when it is null it does not ever use the custom converter.
I did create an example based on you post and this version is correctly writting the LocationRow
object if the AddressObject
is null. All the null values are replaced by an empty string.
Inside the custom converter if the value is null then I'll be returning an empty string.
public override object ConvertFromString(string text, IReaderRow row, MemberMapData memberMapData)
{
var emptyObj = new AddressObject();
// if you are reading back the CSV then additional code should be needed here
return emptyObj;
}
public override string ConvertToString(object value, IWriterRow row, MemberMapData memberMapData)
{
if (value != null && value is AddressObject)
{
var addressObject = value as AddressObject;
return $"{addressObject.City} {addressObject.Road} {addressObject.RoadNumber}";
}
else
{
return "";
}
}
Please take a look at this github repository: https://github.com/bricsi22/csv-helper-example
p.s.: if you know what was the problem please post a comment below this answer, so the community can use this answer more effectively.