简单的数据库表到对象的ORM映射

来源:互联网 发布:达内大数据培训学费 编辑:程序博客网 时间:2024/05/29 23:23

根据微软企业库中数据访问模块改造的一个对象映射类,针对DataRow进行扩展,提供方便的DataTable到对象集合的映射。

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;public static class DataRowExtensions{    /// <summary>    /// 通过数据行创建一个对象    /// </summary>    public static T MapToObject<T>(this DataRow dataRow)    {        Type type = typeof(T);        T convertedObject = System.Activator.CreateInstance<T>();        MapToObject(dataRow, convertedObject);        return convertedObject;    }    /// <summary>    /// 通过行集合创建一个对象列表    /// </summary>    public static List<T> MapToList<T>(this DataRowCollection dataRowCollection)    {        Type type = typeof(T);        List<T> objects = new List<T>();        foreach (DataRow dataRow in dataRowCollection)        {            objects.Add(MapToObject<T>(dataRow));        }        return objects;    }    /// <summary>    /// 通过数据行映射现有对象    /// </summary>    public static void MapToObject(this DataRow dataRow, object convertedObject)    {        Type objectType = convertedObject.GetType();        System.Reflection.PropertyInfo[] properties = objectType.GetProperties();        foreach (System.Reflection.PropertyInfo property in properties)        {            if (dataRow.Table.Columns.Contains(property.Name))            {                object value = dataRow[property.Name];                object convertedValue = ConvertValue(value, property.PropertyType);                property.SetValue(convertedObject, convertedValue, new object[0]);            }        }    }    public static object ConvertValue(object value, Type conversionType)    {        if (IsNullableType(conversionType))        {            return ConvertNullableValue(value, conversionType);        }        return ConvertNonNullableValue(value, conversionType);    }    private static bool IsNullableType(Type t)    {        return t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>);    }    public static object ConvertNonNullableValue(object value, Type conversionType)    {        object convertedValue = null;        if (conversionType.IsEnum)        {            conversionType = Enum.GetUnderlyingType(conversionType);        }        if (value != DBNull.Value)        {            convertedValue = Convert.ChangeType(value, conversionType);        }        return convertedValue;    }    public static object ConvertNullableValue(object value, Type conversionType)    {        if (value != DBNull.Value)        {            var converter = new NullableConverter(conversionType);            return converter.ConvertFrom(value);        }        return null;    }}
原创粉丝点击