SqlHelper简单实现(通过Expression和反射)4.对象反射Helper类
ObjectHelper的主要功能有:
1.通过反射获取Entity的实例的字段值和表名,跳过自增键并填入Dictionary<string,string>中。
1 namespace RA.DataAccess.Common 2 { 3 internal static class ObjectHelper 4 { 5 /// <summary> 6 /// 获取Entity实例的字段名和值(用于更新和插入数据) 7 /// </summary> 8 /// <param name="obj"></param> 9 /// <returns></returns> 10 public static Dictionary<string,object> GetKeyValue(object obj){ 11 var data = new Dictionary<string, object>(); 12 foreach (var i in obj.GetType().GetProperties()) 13 { 14 if (IsContainsAttribute(i.GetCustomAttributes(true))) continue; 15 var value = obj.GetType().GetProperty(i.Name).GetValue(obj, null); 16 data.Add(i.Name, value); 17 } 18 return data; 19 } 20 21 /// <summary> 22 /// 是否包含自增键,在插入表时可以跳过自增键的设置 23 /// </summary> 24 /// <param name="attrs"></param> 25 /// <returns></returns> 26 private static bool IsContainsIndentityAttribute(IEnumerable<object> attrs) 27 { 28 return attrs.OfType<IdentityAttribute>().Any(); 29 } 30 } 31 }
2.通过反射,为实例赋值,此处只是列举了常用的数据类型:int,string和DataTime
1 /// <summary> 2 /// 为通过反射生成的实例赋值 3 /// </summary> 4 /// <typeparam name="T">实例的类型</typeparam> 5 /// <param name="obj">实例</param> 6 /// <param name="value">值</param> 7 /// <param name="key">成员名称</param> 8 public static void SetValue<T>(ref T obj, Object value, String key) where T : class 9 { 10 var property = obj.GetType().GetProperty(key); 11 var type = property.PropertyType.Name; 12 if (value is System.DBNull) 13 { 14 property.SetValue(obj, null, null); 15 return; 16 } 17 switch (type) 18 { 19 case "Int32": 20 property.SetValue(obj, int.Parse(value.ToString()), null); 21 break; 22 case "String": 23 property.SetValue(obj, value.ToString(), null); 24 break; 25 case "DateTime": 26 property.SetValue(obj, (DateTime)value, null); 27 break; 28 default: 29 property.SetValue(obj, value, null); 30 break; 31 } 32 }