• 周日. 11月 27th, 2022

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

DbDataReaderExtensions DbDataRender转换为实体

admin

11月 28, 2021
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GZ.CodeGenerate.DBCore
{
    public static class DbDataReaderExtensions
    {
        public static T GetFieldValue<T>(this DbDataReader render, string fieldname)
        {
            return render.GetFieldValue<T>(render.GetOrdinal(fieldname));
        }

        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)
                    return null;
                System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(conversionType);
                conversionType = nullableConverter.UnderlyingType;
            }
            return Convert.ChangeType(value, conversionType);
        }
    }
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注