C# 通过反射将 DataRow 转为 实体类

public class BaseDAL
{
    /// <summary>
    ///  DataRow转实体类
    /// </summary>
    /// <typeparam name="T">实体类</typeparam>
    /// <param name="row"></param>
    /// <returns>返回实体类的实例</returns>
    public T DataRowToModel<T>(DataRow row)
    {
        try
        {
            T t = default(T);
            PropertyInfo[] propertypes = null;
            string tempName = string.Empty;
            t = Activator.CreateInstance<T>();
            propertypes = t.GetType().GetProperties();
            foreach (PropertyInfo pro in propertypes)
            {
                tempName = pro.Name;
                if (row.Table.Columns.Contains(tempName))
                {
                    DataRowVersion drv;
                    switch (row.RowState)
                    {
                        case DataRowState.Deleted:
                            {
                                drv = DataRowVersion.Original;
                                break;
                            }
                        case DataRowState.Detached:
                            {
                                drv = DataRowVersion.Default;
                                break;
                            }
                        default:
                            {
                                drv = DataRowVersion.Current;
                                break;
                            }
                    }
                    object value = row[tempName, drv];
                    if (value.GetType() == typeof(System.DBNull))
                    {
                        value = null;
                    }
                    pro.SetValue(t, value, null);
                }
            }
            return t;
        }
        catch (Exception e)
        {
            MessageBox.Show("DataRow转换实体类时失败,错误位置:DAL.BaseDAL.DataRowToModel,错误详情:" + e.Message,
                "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            throw new Exception("DataRow转换实体类时失败,错误位置:DAL.BaseDAL.DataRowToModel,错误详情:" + e.Message);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/CodeMJ/article/details/85221324
今日推荐