反射实现查询
电脑版发表于:2020/1/9 17:55
实现任意对象的查询
public static List<T> ToList<T>() { string tableName = typeof(T).Name; string sql = "select * from " + tableName; using (SqlConnection conn = new SqlConnection("server=.;uid=sa;pwd=123456;database=mydb")) { conn.Open(); using (SqlCommand com = new SqlCommand(sql, conn)) { SqlDataReader reader = com.ExecuteReader(); List<T> departments = new List<T>(); while (reader.Read()) { //一个类型通过反射实例化 T obj = Activator.CreateInstance<T>(); //遍历类型所有的公开属性 foreach (var item in obj.GetType().GetProperties()) { string pname = item.Name; //取出来对应属性名查询的value Object value = reader[pname]; if (value != DBNull.Value) { //反射赋值 item.SetValue(obj, value); } } departments.Add(obj); } return departments; } } }
表达式数实现一个简单得条件
表达式数的简单分析
代码:
public static List<T> ToList<T>(Expression<Func<T, bool>> predicate) { string tableName = typeof(T).Name; string sql = "select * from " + tableName + " where "; BinaryExpression binaryExpression = predicate.Body as BinaryExpression; //解析左边(提起名字) MemberExpression memberExpression = binaryExpression.Left as MemberExpression; string name = memberExpression.Member.Name; sql += " " + name; if (binaryExpression.NodeType == ExpressionType.Equal) { sql += " = "; } //解析右边(属性值) string rightvalue = binaryExpression.Right.ToString().Replace("\"", ""); sql += "'" + rightvalue + "'"; using (SqlConnection conn = new SqlConnection("server=.;uid=sa;pwd=123456;database=mydb")) { conn.Open(); using (SqlCommand com = new SqlCommand(sql, conn)) { SqlDataReader reader = com.ExecuteReader(); List<T> departments = new List<T>(); while (reader.Read()) { //一个类型通过反射实例化 T obj = Activator.CreateInstance<T>(); //遍历类型所有的公开属性 foreach (var item in obj.GetType().GetProperties()) { string pname = item.Name; //取出来对应属性名查询的value Object value = reader[pname]; if (value != DBNull.Value) { //反射赋值 item.SetValue(obj, value); } } departments.Add(obj); } return departments; } } }
使用:
List<Department> departments = MyEFContext.ToList<Department>(a => a.DepartmentName == "洗澡服务");