.NET Core 自己封装实现一个 SqlHelper ORM
1 | SqlHelper工具类(实现添加、查询) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | public class SqlHelper { private static string ConnectionStringCustomers = ConfigurationManager.ConnectionStrings[ "Customers" ].ConnectionString; public T Find<T>( int id) where T : BaseModel { Type type = typeof (T); string tableName = type.GetMappingName(); string columnString = string .Join( "," , type.GetProperties().Select(p => $ "[{p.GetMappingName()}]" )); string sql = $ @"SELECT {columnString} FROM [{tableName}] WHERE ID = @Id" ; SqlParameter[] sqlParameterList = new SqlParameter[] { new SqlParameter( "@Id" ,id) }; using (SqlConnection conn = new SqlConnection(ConnectionStringCustomers)) { SqlCommand command = new SqlCommand(sql, conn); command.Parameters.AddRange(sqlParameterList); conn.Open(); var reader = command.ExecuteReader(); if (reader.Read()) { T t = Activator.CreateInstance<T>(); foreach ( var prop in type.GetProperties()) { prop.SetValue(t, reader[prop.GetMappingName()] is DBNull ? null : reader[prop.GetMappingName()]); } return t; } else { return default (T); } } } public bool Insert<T>(T t) where T : BaseModel { Type type = typeof (T); string sql = SqlBuilder<T>.GetSql(); var sqlParameterList = type.GetProperties().Select(p => new SqlParameter($ "@{p.Name}" , p.GetValue(t) ?? DBNull.Value)).ToArray(); using (SqlConnection conn = new SqlConnection(ConnectionStringCustomers)) { SqlCommand command = new SqlCommand(sql, conn); command.Parameters.AddRange(sqlParameterList); conn.Open(); int iResult = command.ExecuteNonQuery(); return iResult == 1; } } } |
使用方法
1 2 3 | SqlHelper helper = new SqlHelper(); Company company1 = helper.Find<Company>(1); helper.Insert<Company>(company1); |
1 | 改进一下实现延迟提交方式,模拟 DBContext |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 | /// <summary> /// 延迟提交式,模拟DBContext /// </summary> public class SqlHelperDelay : IDisposable { /// <summary> /// 通用主键查询操作 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="id"></param> /// <returns></returns> public T Find<T>( int id) where T : BaseModel, new () { Type type = typeof (T); //string columnsString = string.Join(",", type.GetProperties().Select(p => $"[{p.GetMappingName()}]")); //string sql = $"SELECT {columnsString} FROM [{type.GetMappingName()}] WHERE ID={id} "; string sql = $ "{SqlBuilder<T>.GetFindSql()}{id}" ; string connString = SqlConnectionPool.GetConnectionString(SqlConnectionPool.SqlConnectionType.Read); Console.WriteLine($ "当前查询的字符串为{connString}" ); using (SqlConnection conn = new SqlConnection(connString)) { SqlCommand command = new SqlCommand(sql, conn); conn.Open(); var reader = command.ExecuteReader(); if (reader.Read()) { T t = new T(); foreach ( var prop in type.GetProperties()) { string propName = prop.GetMappingName(); //查询时as一下,可以省下一轮 prop.SetValue(t, reader[propName] is DBNull ? null : reader[propName]); //可空类型 设置成null而不是数据库查询的值 } return t; } else { return default (T); } } } private IList<SqlCommand> _SqlCommandList = new List<SqlCommand>(); public void Insert<T>(T t) where T : BaseModel, new () { Type type = t.GetType(); string sql = SqlBuilder<T>.GetInsertSql(); var paraArray = type.GetProperties().Select(p => new SqlParameter($ "@{p.GetMappingName()}" , p.GetValue(t) ?? DBNull.Value)).ToArray(); SqlCommand command = new SqlCommand(sql); command.Parameters.AddRange(paraArray); this ._SqlCommandList.Add(command); } public void SaveChange() { string connString = SqlConnectionPool.GetConnectionString(SqlConnectionPool.SqlConnectionType.Write); if ( this ._SqlCommandList.Count > 0) { using (SqlConnection conn = new SqlConnection(connString)) { conn.Open(); using (SqlTransaction trans = conn.BeginTransaction()) { try { foreach ( var command in this ._SqlCommandList) { command.Connection = conn; command.Transaction = trans; command.ExecuteNonQuery(); } trans.Commit(); } catch (Exception) { trans.Rollback(); throw ; } finally { this ._SqlCommandList?.Clear(); } } } } } public void Dispose() { this ._SqlCommandList?.Clear(); } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?