动态地将数据从datatable添加到现有类 [英] Dynamically add property from datatable to existing class

查看:52
本文介绍了动态地将数据从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;
        }

推荐答案

您无法将成员添加到现有类。你可以做的唯一事情是使用 System.Reflection.Emit 来生成整个类,但它需要生成一个程序集和一个模块,这将需要 TypeBuilder ModuleBuilder AssemblyBuilder ,依此类推;这将是一项非常困难的工作,需要很好的IL知识,发出的代码很难调试。



同时,你可以模块化行为类似到属性的行为,或者更多的JavaScript属性。您可以创建一个字典,例如,由字符串索引的整数值, System.Collections.Generic.Dictionary< string,int> 然后索引的值,即字符串,可以被视为属性名称,索引找到的值将扮演属性值的角色。您可以为N种不同类型创建N个词典,并分别找到它们。更糟糕的解决方案是字典 System.Collections.Generic.Dictionary< string,object> ;它将涵盖所有类型的属性值,但此解决方案将等同于无类型的属性值。无论如何,当然,因为你可以为任何这些词典添加一个键值对,你可以随时添加这样的模拟属性。



但是我不会这样做。这个和真实属性之间的主要区别在于,编译器不会检测到问题,例如,拼错属性name。通过以一组字符串常量的形式静态声明所有属性名称可以缓解此问题,因此这些常量可以通过这些常量名称使用,或者更好的是,您可以使用一些枚举类型,使用 myEnumerationMember.ToString()用作这些属性名称。但是如果你这样做,它将失去在运行时添加属性的可能性。相反,我建议重新考虑您的代码架构。如果我知道你的最终目标,我可能会提出一些其他想法。



-SA
You cannot add a member to an existing class. The only thing you can do about it is using System.Reflection.Emit to generate the whole class, but it will require generation of an assembly and a module, which would require TypeBuilder, ModuleBuilder, AssemblyBuilder, and so on; and this would be quite a difficult work which requires good knowledge of IL, the emitted code is quite hard to debug.

At the same time, you can module behavior similar to the behavior of properties, or, even more, JavaScript properties. You can create a dictionary of, say, integer values indexed by string, System.Collections.Generic.Dictionary<string, int> Then the value of the index, the string, could be considered as a property name, and the value found by index would play the role of property value. You can create N dictionaries for N different types and find them separately. Worse solution would be the dictionary System.Collections.Generic.Dictionary<string, object>; it would cover all types of property values, but this solution would be equivalent to the typeless one. Anyway, of course, as you can add a key-value pair to any of those dictionaries, you can add such emulated "property" at any time.

But I would not do it. Main difference between this and "real" properties is that the compiler won't detect a problem is you, say, misspell the property "name". This problem can be alleviated by having all property names statically declared in the form of a set of string constants, so these constants could be used through those constant names, or, even better, you can use some enumeration type(s), with myEnumerationMember.ToString() used as those property names. But if you do this, it would defeat the possibility of adding properties during runtime. Instead, I would suggest to rethink your code architecture. It's possible that if I knew your ultimate goals, I could suggest some other ideas.

—SA


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

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