2017-07-27 5 views
2

データベースのデータを更新するupdateというメソッドを作成しました。このメソッドは、データベース更新コマンドでメソッドを持つGetUpdateCommandという名前のメソッドを呼び出し、接続文字列を受け取る変数cnを作成しました。接続を開き、トライキャッチして、それを囲むようにしようとしたとき、あなたはあなたがの範囲を閉じている変数メソッドの更新C#の接続エラー

public SqlCommand GetUpdateCommand() 
    { 

     //faz o for em que vai percorrer, traga somente os campos com o atributo customizado do tipo DataObjectFieldAttribute 
     SqlCommand retorno = new SqlCommand(); 
     retorno.CommandText = "Update {0} set {1} where {2}"; 

     String tabela = typeof(T).Name; 
     String campos = ""; 
     String chave = ""; 
     foreach (PropertyInfo pro in typeof(T).GetProperties().ToList().Where(p => p.GetCustomAttribute(typeof(DataObjectFieldAttribute)) != null)) 
     { 
      DataObjectFieldAttribute att = (DataObjectFieldAttribute)pro.GetCustomAttribute(typeof(DataObjectFieldAttribute)); 

      if (att.PrimaryKey==true)//defini a chave primaria no DataObjectField na classe cliente colocando true 
      { 
       chave= pro.Name + "[email protected]" + pro.Name;//pega a chava a chave primaria e adc no parametro 
       retorno.Parameters.AddWithValue("@" + pro.Name, pro.GetValue(this));//adicona os parametros 
      } 
      else 
      { 
       campos += pro.Name + "[email protected]" + pro.Name + ","; 
       retorno.Parameters.AddWithValue("@" + pro.Name, pro.GetValue(this)); 
      } 


     } 
     //retorna com os parametros de acordo com o comando sql do uopdate. 
     retorno.CommandText = String.Format(retorno.CommandText, tabela, campos,chave); 

     return retorno; 


    } 

public void atualizar() 
    { 

     using (SqlConnection cn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|C:\Users\Antonio Viana\documents\visual studio 2017\Projects\Loja\Eccomerce\App_Data\dados.mdf;Integrated Security=True")) ; 
     { 

      SqlCommand cm = this.GetUpdateCommand(); 

      try 
      { 
       cn.Open(); 
      } 
      catch (Exception) 
      { 

       throw; 
      } 

      cm.Connection = cn; 
      cm.ExecuteNonQuery(); 
     } 

    } 
+1

');'がusing' – jAC

答えて

1

を見つけることができませんので、銀行は、しかし、それは、接続で を変数CNを見つけることができません。 using;usingを閉じてオブジェクトの初期化の直後にします。

ので、この行:

using (SqlConnection cn = new SqlConnection(...)) ; 

は次のようになります。

using (SqlConnection cn = new SqlConnection(...)) 
+1

ニーススポット 'の後ろにスコープを閉じ – stuartd

+0

が働い@jACありがとう弟 – Felipe