ORM反射
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; using Dapper; using System.Reflection; namespace DemoOrmHelper { public class OrmHelper<T> where T : class, new() { //连接数据库 SqlConnection conn = new SqlConnection("Data Source=DESKTOP-O7U2DEC;Initial Catalog=B2C;Integrated Security=True"); /// <summary> /// 使用反射,添加的Sql语句 /// </summary> /// <param name="model"></param> /// <returns></returns> public int ExecuteNonQuary(T model) { //获取类型,字段不知道 Type type = model.GetType(); //实例化字符串 StringBuilder stringBuilder = new StringBuilder(); //拼接Sql语句,固定的 stringBuilder.Append($"insert into {type.Name} values ("); //获取字段属性的名称 PropertyInfo[] properties = type.GetProperties(); //循环拼接 foreach (PropertyInfo item in properties) { if(item.Name != "ID") { stringBuilder.Append($"'{item.GetValue(model)}',"); } } //去掉最后一个逗号 string sql = $"{stringBuilder.ToString().TrimEnd(',')})"; int code = conn.Execute(sql); return code; } /// <summary> /// 显示 /// </summary> /// <returns></returns> public List<T> GetList() { //获取类型 Type type = typeof(T); //Sql语句 string sql = $"select * from {type.Name}"; return conn.Query<T>(sql).ToList(); } /// <summary> /// 删除 /// </summary> /// <param name="ID"></param> /// <returns></returns> public int Delete(int ID) { //获取类型 Type type = typeof(T); string sql = $"delete from {type.Name} where ID={ID}"; int code = conn.Execute(sql); return code; } /// <summary> /// 修改 /// </summary> /// <param name="model"></param> /// <returns></returns> public int Update(T model) { //获取类型 Type type = model.GetType(); StringBuilder stringBuilder = new StringBuilder(); //拼接Sql语句,固定的 stringBuilder.Append($"update {type.Name} set "); //获取字段属性的名称 PropertyInfo[] properties = type.GetProperties(); //定义ID,修改的条件 object id = null; foreach (PropertyInfo item in properties) { if(item.Name != "ID") { stringBuilder.Append($"{item.Name}='{item.GetValue(model)}',"); } else { id = item.GetValue(model); } } //去掉最后一个逗号 string sql = $"{stringBuilder.ToString().TrimEnd(',')} where ID={id}"; int code = conn.Execute(sql); return code; } } }