排名
3
文章
317
粉丝
22
评论
14
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:
50010702506256


欢迎加群交流技术

只有一个条件代码很简单:
- 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;
- }
- }
- }
大概的表达式树分析图:
欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739。有需要软件开发,或者学习软件技术的朋友可以和我联系~(Q:815170684)
评价