在C#中将DataRow转换为复杂对象

时间:2019-04-28 09:11:14

标签: c# .net datarow

我创建了如下的复杂类

public class Customer
{
    public int Id { get; set; }
    public List<string> Roles { get; set; }
    public DateTime? CreatedDate { get; set; }
    public List<Address> Address { get; set; }
    public Payment Payment { get; set; }
    public UserStatus Status { get; set; }
}
public class Address
{
    public string Address1 { get; set; }
    public string City { get; set; }
}
public class Payment
{
    public double Amount { get; set; }
    public string TranscationId { get; set; }
}
public enum UserStatus
{
    Active = 1,
    Deactive = 2
}

我在DB上有这样的Customer表结构

Id bigint
Roles varchar(100)
CreatedDate datetime
Address text
Payment text
Status varchar(20)

我有很多像上面这样的对象,所以我为所有人创建了通用函数以将数据行转换为对象

public static T ConvertDataRowToObject<T>(DataRow dr) where T : new()
{
    Type entityType = typeof(T);
    T r = new T();
    foreach (DataColumn column in dr.Table.Columns)
    {
        object value = dr[column.ColumnName];
        if (value == DBNull.Value) value = null;
        PropertyInfo property = entityType.GetProperty(column.ColumnName, BindingFlags.Instance | BindingFlags.IgnoreCase | BindingFlags.Public);
        try
        {
            if (property != null && property.CanWrite)
            {
                Type propertyType = property.PropertyType;
                if (property.PropertyType.IsEnum)
                    value = Enum.ToObject(property.PropertyType, int.Parse(value.ToString()));
                else if(property.PropertyType.IsGenericType && !property.PropertyType.Name.Equals("Nullable`1"))
                    value = value.ToString().Replace("\"","").Replace("[", "").Replace("]", "").Split(',').ToList();

                property.SetValue(r, value, null);
            }

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    return r;
}

谁能帮助我创建将数据行转换为复杂对象的功能 预先谢谢你

0 个答案:

没有答案