今天写了一个数据库的帮助类,代码如下。 

 1 public static class DbEx
 2 {
 3     public static dynamic ReadToObject(this IDataReader reader)
 4     {
 5         var obj = new DbObject();
 6 
 7         for (int i = 0; i < reader.FieldCount; i++)
 8         {
 9             obj[reader.GetName(i)] = new DbField()
10             {
11                 DbData = reader[i]
12             };
13         }
14 
15         return obj;
16     }
17 
18     public class DbObject : DynamicObject
19     {
20         //自己实现一个,不用ExpandoObject, 以支持无视大小写读取
21         public override bool TryGetMember(GetMemberBinder binder, out object result)
22         {
23             result = this[binder.Name];
24             return true;
25         }
26 
27         Dictionary<string, object> _values = new Dictionary<string, object>(StringComparer.CurrentCultureIgnoreCase);
28 
29         public object this[string index]
30         {
31             get => _values[index];
32             set => _values[index] = value;
33         }
34     }
35 
36     public class DbField
37     {
38         public object DbData { get; set; }
39 
40         public T Value<T>()
41         {
42             return (T)Convert.ChangeType(DbData, typeof(T));
43         }
44 
45         public static implicit operator string(DbField data) => data.Value<string>();
46         public static implicit operator int(DbField data) => data.Value<int>();
47         public static implicit operator DateTime(DbField data) => data.Value<DateTime>();
48         public static implicit operator double(DbField data) => data.Value<double>();
49         public static implicit operator bool(DbField data) => data.Value<bool>();
50     }
51 }
View Code

相关文章:

  • 2022-02-15
  • 2021-06-07
  • 2022-12-23
  • 2021-09-21
  • 2022-12-23
  • 2021-05-19
  • 2021-09-14
  • 2021-07-22
猜你喜欢
  • 2022-01-14
  • 2022-12-23
  • 2022-12-23
  • 2022-01-31
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案