DbDataReader转对象


扩展DbDataRender对象,让DbDataRender支持直接转换为对象 DbDataReader.ConvertObject<T>

推荐使用

/// <summary>
/// 
/// </summary>
public static class DbDataReaderExtensions
{
    /// <summary>
    /// 获得字段值
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="render"></param>
    /// <param name="name"></param>
    /// <returns></returns>
    public static T GetFieldValue<T>(this DbDataReader render, string name)
    {
        int origin = render.GetOrdinal(name);
        if (origin >= 0)
            render.GetFieldValue<T>(origin);
        return default(T);
    }
    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="render"></param>
    /// <returns></returns>
    public static T ToObject<T>(this DbDataReader render) where T : new()
    {
        var flags = System.Reflection.BindingFlags.Public
            | System.Reflection.BindingFlags.Instance
            | System.Reflection.BindingFlags.IgnoreCase;

        Type t = typeof(T);
        T data = new T();
        for (int i = 0; i < render.FieldCount; i++)
        {
            string name = render.GetName(i);
            var p = t.GetProperty(name, flags);
            if (p != null)
                p.SetValue(data, CheckType(render[i], p.PropertyType), null);
        }

        return data;

    }
   

    // <summary>
    /// 对可空类型进行判断转换(*要不然会报错)
    /// </summary>
    /// <param name="value">DataReader字段的值</param>
    /// <param name="conversionType">该字段的类型</param>
    /// <returns></returns>
    private static object CheckType(object value, Type conversionType)
    {
        if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
        {
            if (value == null || value == DBNull.Value)
                return null;
            System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(conversionType);
            conversionType = nullableConverter.UnderlyingType;
        }
        return Convert.ChangeType(value, conversionType);
    }
}
GarsonZhang www.yesdotnet.com

 

 

其他

public static class GZExtension
{
        public static string GetString(this DbDataReader row, string name)
        {
                return row.GetValue(row.GetOrdinal(name)).ToString();

        }
        public static T ConvertObject<T>(this DbDataReader dr) where T : new()
        {
                var v = typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);

                DataTable dtColumns = dr.GetSchemaTable();
                Dictionary<string, int> columns = new Dictionary<string, int>();
                foreach (DataRow r in dtColumns.Rows)
                {
                        columns.Add(r["ColumnName"].ToString(), Convert.ToInt32(r["ColumnOrdinal"]));
                }


                T t = new T();
                foreach (var s in v)
                {
                        if (!columns.ContainsKey(s.Name)) continue;
                        int Ordinal = columns[s.Name];

                        object value = dr.GetValue(Ordinal);
                        if (object.Equals(value, DBNull.Value)) continue;
                        try
                        {
                                //s.SetValue(t, dr[s.Name], null);
                                s.setValueEx(t, dr[s.Name]);
                        }
                        catch (Exception e)
                        {
                                throw e;
                        }

                }

                return t;

        }

        public static void setValueEx(this System.Reflection.PropertyInfo property, object obj, object value)
        {
                if (!property.PropertyType.IsGenericType)
                {
                        //非泛型
                        property.SetValue(obj, value == DBNull.Value ? null : Convert.ChangeType(value, property.PropertyType), null);
                }
                else
                {
                        //泛型Nullable<>
                        Type genericTypeDefinition = property.PropertyType.GetGenericTypeDefinition();
                        if (genericTypeDefinition == typeof(Nullable<>))
                        {
                                property.SetValue(obj, value == DBNull.Value ? null : Convert.ChangeType(value, Nullable.GetUnderlyingType(property.PropertyType)), null);
                        }
                }
        }

        public static T ConvertObject<T>(this DataRow dr) where T : new()
        {

                var v = typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);

                T t = new T();
                foreach (var s in v)
                {
                        if (dr.Table.Columns.Contains(s.Name))
                        {
                                if (object.Equals(dr[s.Name], DBNull.Value)) continue;
                                {
                                        s.SetValue(t, dr[s.Name], null);
                                }
                        }

                }

                return t;

        }
}
GarsonZhang www.infnitee.com
版权声明:本文为YES开发框架网发布内容,转载请附上原文出处连接
YES开发框架
上一篇:winform控件截取图像
下一篇:文件或目录损坏且无法读取
评论列表

发表评论

评论内容
昵称:
关联文章

DbDataReader对象
对象和Datatable互
Python对象json字符串
C# 使用Newtonsoft对象JSON字符串的时候日期类型的处理
C#类型转换,对象转换
Python Flask返回JSON字符串,自定义对象JSON字符串
WPF对象级资源
C# 时间戳与 标准时间互
winform绑定对象数据源
C#汉字拼音
Redis OM .NET Redis对象映射框架
C# 十六进制字符串byte[],Byte[] String
C# PNGICO,ICOPNG,PNG图标常规尺寸互
.net异步Task同步
C#代码:byte[] 十六进制字符串
javascript表单Formjson进行ajax提交Jquery表单json提交
EFCore DbContext扩展执行原生SQL查询对象集合
PNG-ICO图标格式互工具
路由跳以及参数处理
软件:批量HEICJPG 苹果手机照片格式JPG

联系我们
联系电话:15090125178(微信同号)
电子邮箱:garson_zhang@163.com
站长微信二维码
微信二维码