动态地将数据从datatable添加到现有类

动态地将数据从datatable添加到现有类

本文介绍了动态地将数据从datatable添加到现有类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正在开发一个WebAPI应用程序。我想动态地将Field / Property添加到现有类中。然后我想绑定数据并从控制器返回原子+ xml / json。

假设

我的类(没有字段/属性)是



Hi,
I am developing an WebAPI Application. I want to add Field/Property dynamically to existing class. then I want to bind with data and return from controller as atom+xml/json.
Suppose that
My Class(Without field/Property) is

public class Category
{

} 





并且tab_Category DataTable返回5行,其值为列值

ID(Int)

代码(字符串)

名称(字符串)

描述(字符串)

IsActive(布尔值)也可以随时从数据库更改列。



这些字段将在运行时自动添加为具有get / set属性的字段到类Category。

结果将是





And the tab_Category DataTable return 5 rows with values where columns are
ID(Int)
Code(String)
Name(String)
Description(String)
IsActive(Boolean) also the columns can be changed any time from database.

these fields will automatically add as field with get/set property to class Category at runtime.
the result will be

public class Category
{
  public int ID {get; set;}
  public string CODE {get; set;}
  . . .
  public bool IsActive {get; set;}
}





请有任何解决方案。那么请给我任何源代码或演示项目帮助我

如果可能的话。请帮帮我!!!



我尝试过:





please is there any solution. then please help me by giving any source code or demo project
if possible. Please help me urgent!!!

What I have tried:

private List<dictionary><string,>> LoadData(string sqlSelect)
        {
            var table = new List<dictionary><string,>>();
            using (var ctx = db)
            {
                ctx.Database.Connection.Open();
                using (var cmd = ctx.Database.Connection.CreateCommand())
                {
                    cmd.CommandText = sqlSelect;
                    //foreach (var param in sqlParameters)
                    //    cmd.Parameters.Add(param);
                    using (var reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            var row = new Dictionary<string,>();
                            for (int i = 0; i < reader.FieldCount; i++)
                                row[reader.GetName(i)] = reader[i];
                            table.Add(row);
                        }
                    }
                }
            }
            return table;
        }

推荐答案


这篇关于动态地将数据从datatable添加到现有类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 23:28