可能重复:
LINQ Single vs First
我是 Linq 的新手,想以最好的方式学习它,我在这里有 2 个用于 linq 的工作更新事件,他们也是这样做的,但是最好的方法是什么,我需要添加一些东西来使它更好!?
解决方案 1
Protected Sub Button2_Click(sender As Object, e As System.EventArgs) Handles Button2.Click
Using db As New ThedatabaseconnectionDataContext()
Try
Dim TheUpdateID = DirectCast(FindControl("Textbox5"), TextBox).Text
Dim getEditing As testtable = (From c In db.testtables Where c.test_id = TheUpdateID Select c).FirstOrDefault()
If getEditing IsNot Nothing Then
getEditing.test_cat = DirectCast(FindControl("Textbox1"), TextBox).Text
getEditing.test_info = DirectCast(FindControl("Textbox2"), TextBox).Text
getEditing.test_number = DirectCast(FindControl("Textbox3"), TextBox).Text
getEditing.test_datetime = DirectCast(FindControl("Textbox4"), TextBox).Text
db.SubmitChanges()
'textBox1.Text = "Contact updated."
End If
Catch ex As Exception
'Me.lblMsg.Text = ex.Message
End Try
End Using
End Sub
解决方案 2
Protected Sub Button2_Click(sender As Object, e As System.EventArgs) Handles Button2.Click
Using db As New ThedatabaseconnectionDataContext()
Try
Dim tbltest As Table(Of testtable) = db.GetTable(Of testtable)()
Dim TheUpdateID = DirectCast(FindControl("Textbox5"), TextBox).Text
Dim getEditing As testtable = tbltest.Single(Function(c) c.test_id = TheUpdateID)
If getEditing IsNot Nothing Then
getEditing.test_cat = DirectCast(FindControl("Textbox1"), TextBox).Text
getEditing.test_info = DirectCast(FindControl("Textbox2"), TextBox).Text
getEditing.test_number = DirectCast(FindControl("Textbox3"), TextBox).Text
getEditing.test_datetime = DirectCast(FindControl("Textbox4"), TextBox).Text
db.SubmitChanges()
'textBox1.Text = "Contact updated."
End If
Catch ex As Exception
'Me.lblMsg.Text = ex.Message
End Try
End Using
End Sub