9

我正在尝试创建一个通用类来保存日志

这里我们使用实体框架,所以假设我们有表 mng_users(string usr_name, int usr_id) 为 itentity 创建相应的类)

有没有办法实现 toDataTable 方法将实体转换为数据表(不是列表,只有 1 行)所以我可以这样做:

将 mng_users1 和 mng_users2 作为 mng_users 实体类(都具有相同的 id 但名称不同)

调用方法“保存日志(mng_users1,mng_users2);” 并执行以下代码:

    private DataTable toDataTable(Object T)
    {
        DataTable vDataTable = new DataTable();

        //AddColums here
        //AddRow with the respective values here

        return vDataTable;
    }

    public void savelog(Object newObject, Object oldObject)
    {

        DataTable newvalue, oldvalue;

        newvalue = toDataTable(newObject);
        oldvalue = toDataTable(oldObject);

       string FieldNames = string.Empty, FieldValuesFrom = string.Empty, FieldValuesTo = string.Empty;
       foreach (DataColumn item in newvalue.Columns)
                {
                    if (newvalue.Rows[0][item].ToString() != oldvalue.Rows[0][item].ToString())
                    {
                        FieldNames += (FieldNames.Length > 0 ? " | " : string.Empty) + item.ColumnName;
                        FieldValuesFrom += (FieldValuesFrom.Length > 0 ? " | " : string.Empty) + newvalue.Rows[0][item].ToString();
                        FieldValuesTo += (FieldValuesTo.Length > 0 ? " | " : string.Empty) + oldvalue.Rows[0][item].ToString();
                    }

                }
        // Save log to sql code here
    }
4

2 回答 2

12

类似下面的代码应该可以工作。它可能需要根据属性是否private/protected以及是否有任何公共属性被索引进行调整,但它应该可以帮助您入门。

private DataTable ToDataTable<T>(T entity) where T : class
{
   var properties = typeof(T).GetProperties();
   var table = new DataTable();

   foreach(var property in properties)
   {
       table.Columns.Add(property.Name, property.PropertyType);
   }

   table.Rows.Add(properties.Select(p => p.GetValue(entity, null)).ToArray());
   return table;
}
于 2012-11-28T13:56:47.943 回答
9

我对上述示例的改进:

  • 将语法更改为扩展方法
  • 现在扩展方法将现有对象实体列表转换为 DataTable
  • 添加了对 Nullable 属性类型的支持

    public static DataTable ToDataTable<T>(this IEnumerable<T> entityList) where T : class
    {
        var properties = typeof(T).GetProperties();
        var table = new DataTable();
    
        foreach (var property in properties)
        {
            var type = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
            table.Columns.Add(property.Name, type);
        }
        foreach (var entity in entityList)
        {
            table.Rows.Add(properties.Select(p => p.GetValue(entity, null)).ToArray());
        }
        return table;
    }
    
于 2015-05-22T09:45:32.787 回答