public T Query<T>(int id) where T : BaseModel { Type type = typeof(T); string columnString = string.Join(",", type.GetProperties().Select(p => $"[{p.GetColumnName()}]")); string sql = $"SELECT {columnString} FROM [{type.Name}] WHERE Id=@Id"; T t = default(T); DataTable dt = new DataTable(); Func<SqlCommand, T> func = (SqlCommand command) =>//1 将要执行的先准备好 { SqlParameter para = new SqlParameter("@Id", id);//3 func.invoke(command) 执行这里并返回 command.Parameters.Add(para); SqlDataAdapter adapter = new SqlDataAdapter(command); //SqlDataReader reader = command.ExecuteReader(); //List<T> list = this.ReaderToList<T>(reader); adapter.Fill(dt); List<T> list = ConvertToList<T>(dt); T tResult = list.FirstOrDefault(); return tResult; }; t = ExcuteSql<T>(sql, func); return t; } private T ExcuteSql<T>(string sql, Func<SqlCommand, T> func) { using (SqlConnection conn = new SqlConnection(strConn)) { using (SqlCommand command = new SqlCommand(sql, conn)) { conn.Open(); SqlTransaction sqlTransaction = conn.BeginTransaction(); try { command.Transaction = sqlTransaction; T tResult = func.Invoke(command);//2执行前面准备好的。 sqlTransaction.Commit(); return tResult; } catch (Exception ex) { sqlTransaction.Rollback(); throw; } } } }
标签:string,委托,C#,tResult,command,func,new,conn From: https://www.cnblogs.com/liujian1368928/p/17104314.html