如何将DataRow转换为对象

15

我在我的项目中创建了一个DataRow:

DataRow datarow;

我想将这个DataRow转换为任何类型的对象,应该怎么做?


DataRow默认是一个对象。你想要实现什么目标? - IDeveloper
@IDeveloper 我想将数据行转换为给定类型的对象,并带有值。 - folk
1
Entity Framework 怎么样? - OneFineDay
@DonA 我对Entity Framework一无所知。 - folk
“Entity Framework” 将数据库转换成一组具有属性的强类型类 - 很棒的东西!Google一下吧! - OneFineDay
11个回答

-1

对于 int、long、int? 和 long? 字段,这些更改对我来说都很好用。

// function that creates an object from the given data row
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)
    {
        // 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)
        {
            if (p.PropertyType.Name == "Int64")
            {
                p.SetValue(item, long.Parse(row[c].ToString()), null);
            }
            else if (p.PropertyType.Name == "Int32")
            {
                p.SetValue(item, int.Parse(row[c].ToString()), null);
            }
            else if (p.PropertyType.FullName.StartsWith("System.Nullable`1[[System.Int32"))
            {
                p.SetValue(item, (int?)int.Parse(row[c].ToString()), null);
            }
            else if (p.PropertyType.FullName.StartsWith("System.Nullable`1[[System.Int64"))
            {
                p.SetValue(item, (long?)long.Parse(row[c].ToString()), null);
            }
            else
            {
                p.SetValue(item, row[c], null);
            }
        }
    }
}

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