Click here to Skip to main content
15,884,472 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
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?
Posted
Comments
Richard Deeming 9-Jun-15 11:04am    
I appreciate that English might not be your native language, but saying "Now pay attention here" sounds rather rude and condescending.

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...
C#
// 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'
 
Share this answer
 
Comments
kailash_tandel87 9-Jun-15 10:45am    
This is two time conversion method. First from datareader data to json and then json to class. Its not feasible solution. Because I have big data so its a time consuming method.
Use Dapper[^], mapping to a list of dynamic objects:


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


This method will execute SQL and return a dynamic list.

Example usage:
C#
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);

 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900