将DataTable转换为强类型对象列表

4
我将尝试编写一个通用方法,将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作为其中一个参数,以便我可以传递一些映射信息吗?


2
可能是重复的问题,链接为 https://dev59.com/ekbRa4cB1Zd3GeqPyTo8 和 http://stackoverflow.com/q/5856634/490018。 - Sergey Vyacheslavovich Brunov
2个回答

8

我认为使用“扩展方法(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
@jdavis 我更新了我的答案,提供了一种更符合你需求的方法。如果有帮助,请告诉我。 - Sorax

0

对 @Sorax 的回答进行补充。我增强了 ToType 方法,以支持 Nullable<> 类型成员(使用字段而不是属性和 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。 - TWilly

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接