利用泛型和反射,将从数据库select出来的集合直接转换成对象
2012-06-30 17:55
591 查看
现在的版本是直接利用反射的,下一步将改编成利用快速反射 public static T ExcuteEntity<T>(SQLiteCommand cmd) { Type entityType = typeof(T); PropertyInfo[] fieldinfos = entityType.GetProperties(); T entity = (T)Activator.CreateInstance(entityType); DbDataReader reader = null; if (conn == null || conn.Length == 0) throw new ArgumentNullException("connectionString"); SQLiteConnection con = new SQLiteConnection(conn); SQLiteTransaction trans = null; PrepareCommand(cmd, con, ref trans, false, cmd.CommandType, cmd.CommandText); try { reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); reader.Read(); } catch (Exception ex) { throw ex; } foreach (PropertyInfo field in fieldinfos) { int col=reader.GetOrdinal(field.Name); if (col != -1) { Type mytype = reader.GetFieldType(col); entityType.GetProperty(field.Name).SetValue(entity, Convert.ChangeType(reader.GetValue(col), mytype), null); } else { continue; } } return entity; } public static List<T> ExecuteCollection<T>(SQLiteCommand cmd) { List<T> result = new List<T>(); Type entityType = typeof(T); PropertyInfo[] fieldinfos = entityType.GetProperties(); DbDataReader reader = null; if (conn == null || conn.Length == 0) throw new ArgumentNullException("connectionString"); SQLiteConnection con = new SQLiteConnection(conn); SQLiteTransaction trans = null; PrepareCommand(cmd, con, ref trans, false, cmd.CommandType, cmd.CommandText); try { reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); } catch (Exception ex) { throw ex; } while (reader.Read()) { T entity = (T)Activator.CreateInstance(entityType); foreach (PropertyInfo field in fieldinfos) { int col = reader.GetOrdinal(field.Name); if (col != -1) { Type mytype = reader.GetFieldType(col); entityType.GetProperty(field.Name).SetValue(entity, Convert.ChangeType(reader.GetValue(col), mytype), null); } else { continue; } } result.Add(entity); } return result; }
相关文章推荐
- 利用泛型和反射对Java对象集合转换成Json的工具类
- 利用反射和泛型把Model对象按行储存进数据库以及按行取出然后转换成Model 类实例 MVC网站通用配置项管理
- DataTable和DataRow利用反射直接转换为Model对象的扩展方法类
- C#中利用LINQ to XML与反射把任意类型的泛型集合转换成XML格式字符串的方法
- C#中利用LINQ to XML与反射把任意类型的泛型集合转换成XML格式字符串的方法
- 反射创建对象,创建泛型集合,创建泛型字典
- 使用java反射将数据库结果集转换成对象结果集
- [导入]利用OleDb对象,将数据库中全部表转换成XML文件
- 利用OleDb对象,将数据库中全部表转换成XML文件
- 在一般处理程序中,把Form Post过来的表单集合转换成对象 ,仿 MVC post,反射原理
- json串中的对象集合如何转换出来
- 利用java反射将结果集封装成为对象和对象集合
- 利用OleDb对象,将数据库中全部表转换成XML文件
- 【java】反射(二)——泛型集合(在ArrayList<Integer>中加入String对象)
- 利用反射实现mysql数据库sql查询 返回List<E>泛型(持久化)对象
- 运用反射原理的简单工厂模式和运用反射原理从数据库里读出数据直接封装到实体集合里
- 利用OleDb对象,将数据库中全部表转换成XML文件
- 利用反射实现简单的Class对象和Bson文档的转换
- android中利用java反射原理将对象添加到sqlit数据库的万能方法
- 从数据库查询出来的数据集合转换成 json 类型