Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize dynamic Dapper result to CSV

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?

like image 513
NATO24 Avatar asked Mar 04 '26 00:03

NATO24


2 Answers

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.

like image 187
mythz Avatar answered Mar 05 '26 12:03

mythz


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.

like image 40
Marc Gravell Avatar answered Mar 05 '26 14:03

Marc Gravell