排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:50010702506256
欢迎加群交流技术
分类:
mvc
只有一个条件代码很简单:
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; } } }
大概的表达式树分析图:
欢迎加群讨论技术,群:677373950(满了,可以加,但通过不了),2群:656732739
评价