ORM:对象关系映射Object Relational Mapping(简称ORM)
如果数据库对应几十个实体类就是几十个表该怎么查询呢
利用反射加泛型手写ORM
建好数据库Student
先配置好数据库连接
<connectionStrings> <add name="Student" connectionString="server=.; Database=Student;uid=sa;pwd=123;"/> </connectionStrings>
创建sqlserverDBhelper类,编写方法:
public T select<T>(int id) { Type type = typeof(T);//获取到具体类型 string filedstring=string.Join(",",type.GetProperties().Select(c => string.Format("[{0}]", c.Name)));//根据type获取到属性名称,用逗号连接起来便于查询 string tableName = type.Name;//获取到表名 object obj = Activator.CreateInstance(type);//初始化字段赋原始值 string sql = string.Format("select {0} from {1} where ID={2} ",filedstring,tableName,id); SqlCommand cmd = new SqlCommand(sql,conn); if(conn.State==System.Data.ConnectionState.Closed) { conn.Open(); } SqlDataReader reader=cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection); if(reader.Read())//如果读取到数据 { foreach (var item in type.GetProperties())//获取属性 { object ovule = reader[item.Name];//通过reader获取字段名称的值 item.SetValue(obj, ovule);//给每一个字段赋值 Console.WriteLine("{0}:{1}", item.Name, item.GetValue(obj)); } } conn.Close(); return (T)obj; }
局部变量信息:
调用:
sqlserverDBhelper sqlserverD = new sqlserverDBhelper();//实例化 sqlserverD.select<Student>(1); //指定实体类Student ID参数
效果: