将datareader转换为类 [英] convert datareader to class

查看:78
本文介绍了将datareader转换为类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hello Developers,



我有一个datareader。我想将该datareader数据转换为类b $ b。现在请注意,我没有'我的班级

身体存在。我想动态地根据datareader数据创建具有属性

的类。



例如datareader列将成为类属性

,值将成为类属性值。



我能够将datareader转换为Dictionary和List但是

不是直接到动态类。



我想将datareader转换为动态类和

类将成为wcf方法的响应类型。我想要

发送该类作为我的WCF方法的响应。



请建议我怎么做?

Hello Developers,

I have a datareader. I want to convert that datareader data
to class. Now pay attention here, I dont' have my class
physically exists. I want to create that class with property
according to the datareader data dynamically.

E.g. the datareader column will become class property
and value will become class property value.

I am able to convert datareader to Dictionary and List but
not directly to the dynamic class.

I want to convert datareader into dynamic class and that
class will become the wcf method response type. Means I want
to send that class as response of my WCF method.

Please suggest me how to do this?

推荐答案

我的建议是将每一行数据转换为JSON字符串,然后使用一些JSON库从中创建一个动态类...

My proposal is to turn each and every row of data into a JSON string, then use some JSON library to create a dynamic class from it...
// this is from your data
string json = @"{
  'Name': 'Bad Boys',
  'ReleaseDate': '1995-4-7T00:00:00',
  'Genres': [
    'Action',
    'Comedy'
  ]
}";

dynamic dyn = Newtonsoft.Json.JsonConvert.DeserializeObject(json);

Console.WriteLine(dyn.Name); // will print 'Bad Boys'

使用 Dapper [ ^ ],映射到动态对象列表:



Use Dapper[^], mapping to a list of dynamic objects:




public static IEnumerable<dynamic> Query (this IDbConnection cnn, string sql, object param = null, SqlTransaction transaction = null, bool buffered = true)





此方法将执行SQL并返回一个动态列表。



示例用法:



This method will execute SQL and return a dynamic list.

Example usage:

var rows = connection.Query("select 1 A, 2 B union all select 3, 4").ToList();
((int)rows[0].A).IsEqualTo(1);
((int)rows[0].B).IsEqualTo(2);
((int)rows[1].A).IsEqualTo(3);
((int)rows[1].B).IsEqualTo(4);





这篇关于将datareader转换为类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆