CsvHelper
CsvHelper copied to clipboard
CsvHelper.WriterException: 'No properties are mapped for type 'IData'
Describe the bug
I have a interface IData
and 2 classes that implement this interface.
I need to pass a list of IData
to the CsvWriter.
I am getting the below error
CsvHelper.WriterException: 'No properties are mapped for type 'IData'
The function WriteRecordsAsync
is considering the IData
as the type of the list and not the class that implement the interface.
I am not sure if there is another way to solve this problem or is it possible to have another WriteRecordsAsync
function where we can specify the type.
To Reproduce
interface IData { }
class Person : IData
{
public DateTime DOB { get; set; }
public string? Name { get; set; }
}
class Student : IData
{
public int Id { get; set; }
public string? Name { get; set; }
}
List<IData> list = new List<IData>();
for (int i = 0; i < 100; i++)
{
Person pe = new Person();
pe.DOB = DateTime.Now;
pe.Name = "Ghyath";
list.Add(pe);
}
var result = await WriteToCsv(list);
async Task<string> WriteToCsv<T>(List<T> list) where T : IData
{
string fileContent = string.Empty;
if (list.Count > 0)
{
using var swriter = new StringWriter();
using var csv = new CsvWriter(swriter, CultureInfo.InvariantCulture);
await csv.WriteRecordsAsync<T>(list);
fileContent = swriter.ToString();
csv.Flush();
}
return fileContent;
}
The function
WriteRecordsAsync
is considering theIData
as the type of the list and not the class that implement the interface.
That's because it is. Using csv.WriteRecords((IEnumerable)list)
might work for you.