如何从数据库表动态创建类和属性

问题描述 投票:0回答:2

我需要从数据库表(员工)动态创建类和属性。

我需要在运行时创建一个类和属性并为属性赋值

例如

public class Employee
{
    private int _Id;

    public int Id
    {
        get { return _Id; }
        set { _Id = value; }
    }

    private String _Code;

    public String Code
    {
        get { return _Code; }
        set { _Code = value; }
    }
}

然后我需要访问对象上的这个类

List<Employee> objlstEmp = new List<Employee>();
Employee objEmp = new Employee();
objEmp.Id = 1;
objEmp.Code = "Emp01";
objlstEmp.Add(objEmp);
c# sql-server orm
2个回答
0
投票

正如其他人评论的那样,从你的示例来看,你不需要在运行时生成类,而是使用 ORM 框架并在设计时进行。

由于您似乎不熟悉该主题,因此我建议您研究Entity Framework,并且因为您已经有一个数据库,所以可以从中生成模型。查看如何从数据库创建模型


0
投票

假设您的类在程序集中定义,并且类属性名称等于表中的字段名称。这会有所帮助...

    public static T CreateItemFromRow<T>(DataRow row) where T : new()
    {
        // create a new object
        T item = new T();

        // set the item
        SetItemFromRow(item, row);

        // return 
        return item;
    }
    public static void SetItemFromRow<T>(T item, DataRow row) where T : new()
    {
        // go through each column
        foreach (DataColumn c in row.Table.Columns)
        {
            try
            {
                // find the property for the column
                PropertyInfo p = item.GetType().GetProperty(c.ColumnName);

                // if exists, set the value
                if (p != null && row[c] != DBNull.Value)
                {
                    p.SetValue(item, row[c], null);
                }
                else if (p != null && row[c] == DBNull.Value)
                {
                    if (p.PropertyType == typeof(DateTime?))
                    {
                        p.SetValue(item, DateTime.MinValue, null);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex; //catch what you wish
            }
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.