Possible Duplicate:
LINQ Single vs First
Im new to Linq and want to learn it the best way, I have here 2 working update events for linq, thay do the same, but what way is the best and do i need to add something to make it better !?
Solution 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
Solution 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
Where to even start on this one…
For a start, I know this is likely a test project, so apologies if you’re already doing this, but please make sure you’re using acceptable data tier hierarchies – your DBML should be in a separate project from your Presentation layer.
But, to the question in hand. My preferred way of doing this is getting the data object and updating it on an object level. Such as (pseudo code / I’m a C# kinda guy!):
This makes use of object tracking, and the Daya Layer can then look like this: