Convert rows from a data reader into typed results

后端 未结 10 2284
醉梦人生
醉梦人生 2020-11-27 11:53

I\'m using a third party library which returns a data reader. I would like a simple way and as generic as possible to convert it into a List of objects.
For example, say

10条回答
  •  情话喂你
    2020-11-27 12:47

    Like Magic

    I personally HATE doing manual mapping in constructors, I'm also not a fan of doing my own reflection. So here's another solution courtesy of the wonderful (and fairly ubiquitous) Newtonsoft JSON lib.

    It will only work if your property names exactly match the datareader column names, but it worked well for us.

    ...assumes you've got a datareader name "yourDataReader"...

            var dt = new DataTable();
            dt.Load(yourDataReader);
            // creates a json array of objects
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(dt);
            // this is what you're looking for right??
            List list = 
    Newtonsoft.Json.JsonConvert
    .DeserializeObject>(json);
    

提交回复
热议问题