ahmed elbarbary

ahmed elbarbary

  • NA
  • 1.6k
  • 254.2k

How is wrong on function ExecuteNonQuery to work as Best Pra

Jun 12 2020 8:11 PM

I work on c# app I need to make function make insert data or update or delete dynamically so that I do function below for insert

or update or delete but I don't know what must added or remove from function below to make function work as best practice .
  1. public static async Task<int> ExecuteNonQuery(string sql, SqlConnection sqlconnection, DbParameter[] @params = null, CommandType cmdType = CommandType.StoredProcedure)  
  2.     {  
  3.         int RecordsCount = 0;  
  4.         
  5.   
  6.             if (sql == ""return 0;  
  7.             await Task.Run(async () =>  
  8.             {  
  9.                 using (var con = new SqlConnection(GlobalVariables.con))  
  10.                 {  
  11.                     using (var cmd = new SqlCommand() { Connection = con })  
  12.                     {  
  13.   
  14.   
  15.                         if (cmd.CommandTimeout < 360)  
  16.                             cmd.CommandTimeout = 360;  
  17.                         cmd.CommandText = sql;  
  18.                         cmd.CommandType = cmdType;  
  19.                         cmd.Parameters.Clear();  
  20.                         if (@params != null)  
  21.                         {  
  22.                             for (int i = 0; i < @params.Length; i++)  
  23.                             {  
  24.                                 cmd.Parameters.Add(@params[i]);  
  25.                             }  
  26.                         }  
  27.                         try  
  28.                         {  
  29.                             await con.OpenAsync();  
  30.   
  31.                            RecordsCount = (await cmd.ExecuteNonQueryAsync());  
  32.                         }  
  33.                         catch (Exception ex)  
  34.                         {  
  35.                             throw new Exception(ex.Message);  
  36.                         }  
  37.                     }  
  38.   
  39.                 }  
  40.                   
  41.   
  42.             });  
  43.         return RecordsCount;  
  44.     }  

so I do function above for make insert or update or delete

what is remaining or wrong to be best practice ?

 

Answers (1)