使用LINQ在一个方法中优化插入和更新的代码?

时间:2017-01-18 03:29:51

标签: vb.net linq

我有一个包含Textboxes的表单和包含对象属性的其他控件。插入和更新都使用此表单;变量updatingId(行的唯一ID)仅在更新时分配了值。

“保存”按钮会是这样的:

    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 个答案:

答案 0 :(得分: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