I'm trying to serialize a dynamic Dapper result to CSV using ServiceStack.Text, but I'm getting a collection of line breaks. According to ServiceStack.Text, it can handle both anonymous and IDictionary<string, object>
types.
using (var conn = new SqlConnection(...))
{
var data = conn.Query("select * from data");
var output = CsvSerializer.SerializeToCsv(data);
Console.WriteLine(output);
Console.Read();
}
When I use the same type, it works.
IEnumerable<dynamic> list = new List<dynamic>
{
new
{
Name = "Nathan",
Id = 1,
Created = DateTime.UtcNow
}
};
Console.WriteLine(CsvSerializer.SerializeToString(list));
Console.Read();
What am I missing about Dapper's return type?
I know I can solve this by projecting onto a model class, but the beauty of my approach lies in the use of dynamics. Do I have any options?
dynamic Generic IDictionary's like what Dapper returns should now be supported from this commit.
This change is available from v4.0.43+ that's now available on MyGet.
Dapper's Query
method returns IEnumerable<dynamic>
, which is basically: IEnumerable<object>
- where each row happens to implement IDictionary<string,object>
. I wonder whether SS is looking for the T
is IEnumerable<T>
: in which case, yeah, that won't work well. You could try:
var typed = data.Select(x => (IDictionary<string,object>)typed);
var output = CsvSerializer.SerializeToCsv(typed);
This does the cast in the projection, so that if SerializeToCsv
is a generic method, it'll know about the interface support.
Dapper does not return anonymous types.