2017-01-18 1 views
1

私はテキストボックスとオブジェクトのプロパティを含む他のコントロールを持つフォームを持っています。挿入と更新の両方がこの形式を使用します。変数updatingId(行の一意のID)には、更新時に値が割り当てられます。LINQを使用した1つのメソッドで挿入と更新用に最適化されたコードはありますか?

「保存」ボタンは、このようなものだろう:あなたが見ることができるように

Using db As New DBDataContext 
     Dim wrestlerEntity As New wrestler 
     With wrestlerEntity 
      .alias_1 = TextBox1.Text 
      .alias_2 = TextBox2.Text 
      .stage_name = TextBox3.Text 'etc... 
     End With 

     'Insert/update 
     If updatingId Is Nothing Then 
      'Insert 
      db.wrestlers.InsertOnSubmit(wrestlerEntity) 
     Else 
      'Update 
      Dim updatingRow = (From a In db.wrestlers 
           Where a.ID = updatingId 
           Select a).Single 

      'With updatingRow 
      ' .alias_1 = TextBox1.Text 
      ' .alias_2 = TextBox2.Text 
      ' .stage_name = TextBox3.Text 
      'End With 
     End If 

     'Execute 
     db.SubmitChanges() 
    End Using 

を、更新ブロック(コメントアウト)上のコードは、基本的には、上部にwrestlerEntityの初期設定からコピー&ペーストされます。これを達成するためのより簡単な方法はありますか?私は推測を試みました:

updatingRow = wrestlerEntity 

...無駄に。ありがとう!

答えて

1

古典的なアプローチは、繰り返し文を実行するためにFunction(というか、Sub)を作ることです。

Private Sub PerformAct(entity As wrestler) 
    With entity 
     .alias_1 = TextBox1.Text 
     .alias_2 = TextBox2.Text 
     .stage_name = TextBox3.Text 'etc... 
    End With 
    End Sub 

したがって、あなたが次のようにあなたのメインブロックを簡素化することができます:

Using db As New DBDataContext 
    Dim wrestlerEntity As New wrestler 
    PerformAct(wrestlerEntity) 

    'Insert/update 
    If updatingId Is Nothing Then 
     'Insert 
     db.wrestlers.InsertOnSubmit(wrestlerEntity) 
    Else 
     'Update 
     Dim updatingRow = (From a In db.wrestlers 
          Where a.ID = updatingId 
          Select a).Single 
     PerformAct(updatingRow) 
    End If 

    'Execute 
    db.SubmitChanges() 
End Using 

そして、あなた何度でも何度でもPerformActを再利用できます

+0

クール!だから私はマネージャー、コーチなどのために他のフォームを持っていると考えて、行く方法は 'PerformAct'の独自のバージョンを作成することです? – AwonDanag

+0

@AwonDanagはい、他のフォームの 'PerformAct'の中で何か共通の繰り返しがある場合、同様の繰り返しブロックに対して' Sub'や 'Function'を作成することができます。ポイントは重複することを減らすことであり、 'Function'または' Sub' – Ian

関連する問題