【问题标题】:Convert DataTable to List of strongly typed objects将 DataTable 转换为强类型对象列表
【发布时间】:2012-02-08 18:42:55
【问题描述】:

我正在尝试编写一个将 DataTable 转换为强类型对象列表的通用方法。

到目前为止,我正在使用的代码是...

public List<T> ImportTable<T>(String fileName, String table)
{
    //Establish Connection to Access Database File
    var mdbData = new ConnectToAccess(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\ACCESS\" + fileName + ".mdb;");

    var tableData = new List<T>();

    foreach (DataRow row in mdbData.GetData("SELECT * FROM " + table).Rows)
    {
        tableData.Add(ConvertRowToType<T>(row));
    }

    return tableData;
}

public T ConvertRowToType<T>(DataRow row)
{
    //??? What is the best thing to do here ???        
}

如果有人的建议需要更改它,我不会关注此代码。

假设我调用这个函数传入类型...

public class mdbConcern
{
    public Int32 ConcernId { get; set; }
    public String Concern { get; set; }
}

DataTable 中返回的数据看起来像...

ConcernID  Concern
1          Law and Ethics
2          Mail
3          Business English
...        ...

实现 ConvertRowToType(DataRow row) 方法的最佳方法是什么?

谁能告诉我如何使用 Func 作为参数之一,以便我可以传入一些映射信息?

【问题讨论】:

标签: c# .net generics reflection ado.net


【解决方案1】:

我认为extension method 是最好的选择:

public static class Helper
{
    public static T ToType<T>(this DataRow row) where T : new()
    {
        T obj = new T();
        var props = TypeDescriptor.GetProperties(obj);
        foreach (PropertyDescriptor prop in props)
        {
            if(row.Table.Columns.IndexOf(prop.Name) >= 0 
                && row[prop.Name].GetType() == prop.PropertyType)
            {   
                prop.SetValue(obj, row[prop.Name]);
            }
        }
        return obj;
    }
}

用法:

public List<T> ImportTable<T>(String fileName, String table)
{
    //Establish Connection to Access Database File
    var mdbData = new ConnectToAccess(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\ACCESS\" + fileName + ".mdb;");

    var tableData = new List<T>();

    foreach (DataRow row in mdbData.GetData("SELECT * FROM " + table).Rows)
    {
        tableData.Add(row.ToType<T>());
    }

    return tableData;
}

更新我看到您要求提供映射的Func。我不确定您的设想是什么,但这是我想出的一种方法:

public class mdbConcern
{
    public Int32 ConcernId { get; set; }
    public String Concern { get; set; }

    public static PropertyDescriptor Mapping(string name)
    {
        PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(mdbConcern));
        switch (name)
        {
            case "Concern_Id":
                return props.GetByName("ConcernId");
            case "Concern":
                return props.GetByName("Concern");
            default:
                return null;
        }
    }
}

public static class Helper
{
    public static T ToType<T>(this DataRow row, Func<string, PropertyDescriptor> mapping) 
       where T : new()
    {
        T obj = new T();        
        foreach (DataColumn col in row.Table.Columns)
        {
            var prop = mapping(col.ColumnName);
            if(prop != null)
                prop.SetValue(obj, row[col]);
        }
        return obj;
    }
}

用法:

foreach (DataRow row in mdbData.GetData("SELECT * FROM " + table).Rows)
{
    tableData.Add(row.ToType<mdbConcern>(mdbConcern.Mapping));
}

这是一个使用类型属性的属性来存储其映射的版本。我认为这是一个更自然的解决方案:

[AttributeUsage(AttributeTargets.Property)]
public class ColumnMappingAttribute : Attribute
{
    public string Name { get; set; }
    public ColumnMappingAttribute(string name)
    {
        Name = name;
    }
}
public class mdbConcern
{
    ColumnMapping("Concern_Id")]
    public Int32 ConcernId { get; set; }
    ColumnMapping("Concern")]
    public String Concern { get; set; }
}

public static class Helper
{   
    public static T ToType<T>(this DataRow row) where T : new()
    {
        T obj = new T();
        var props = TypeDescriptor.GetProperties(obj);
        foreach (PropertyDescriptor prop in props)
        {
            var columnMapping = prop.Attributes.OfType<ColumnMappingAttribute>().FirstOrDefault();

            if(columnMapping != null)
            {
                if(row.Table.Columns.IndexOf(columnMapping.Name) >= 0 
                    && row[columnMapping.Name].GetType() == prop.PropertyType)
                {               
                    prop.SetValue(obj, row[columnMapping.Name]);
                }
            }
        }
        return obj;
    }
}

【讨论】:

  • 这是一个简洁的代码示例,但不幸的是,我认为它不适用于我的情况。我从中提取的数据源是一个旧的 Access 数据库,整个架构中的许多列名中都有空格。因此,我的对象上的属性并不都与它们应该对应的表中的列名匹配。
  • @jdavis 我用一种我认为更像您正在寻找的方法更新了我的答案。如果有帮助,请告诉我。
【解决方案2】:

除了@Sorax 答案。我增强了ToType 方法以支持Nullable&lt;&gt; 类型成员(使用字段而不是属性和TypeInfo 而不是TypeDescriptor)。它将整个DataTable 对象作为参数并返回IList。

    protected IList<TResult> TableToList<TResult>(DataTable table) where TResult : new()
    {
        var result = new List<TResult>(table.Rows.Count);

        var fields = typeof(TResult).GetTypeInfo().DeclaredFields;

        TResult obj;
        Object colVal;
        var columns = table.Columns;
        var nullableTypeDefinition = typeof(Nullable<>);
        var dbNullType = typeof(DBNull);
        Type[] genericArguments;

        foreach (DataRow row in table.Rows)
        {
            obj = new TResult();

            foreach (var f in fields)
            {
                if (columns.Contains(f.Name))
                {
                    colVal = row[f.Name];
                    if (colVal.GetType() == f.FieldType)
                    {
                        f.SetValue(obj, colVal);
                    }
                    else if (colVal.GetType() != dbNullType && f.FieldType.IsGenericType && 
                             f.FieldType.GetGenericTypeDefinition() == nullableTypeDefinition)
                    {
                            genericArguments = f.FieldType.GetGenericArguments();

                            if (genericArguments.Length > 0 && genericArguments[0] == colVal.GetType())
                            {
                                f.SetValue(obj, colVal);
                            }
                    }
                }
            }

            result.Add(obj);
        }

        return result;
    }

【讨论】:

  • 我在您的代码的以下行出现错误 var fields = typeof(TResult).GetTypeInfo() 此处无法访问私有方法 GetTypeInfo
猜你喜欢
  • 1970-01-01
  • 2016-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-16
  • 1970-01-01
  • 2012-08-29
  • 1970-01-01
相关资源
最近更新 更多