Hello,
As mentioned already, it's difficult to put together your code in respects to seeing if parts not shown may be an issue. The following is a pattern to consider.
- Use a single local method connection for each operation which uses a static connection string
- As shown below, this checks for errors and if the primary key was not located
- Captures the exception if any.
Here the data operation class, Contact class and Enum are all in the same code block but for a real app would be broken apart. The database is server based but that will not matter as in your case you can connect.
Imports System.Data.SqlClient
Public Class DataOperations
Private Shared ConnectionString As String =
"Data Source=.\SQLEXPRESS;" &
"Initial Catalog=NorthWind2020;" +
"Integrated Security=True"
Public Shared LastException As Exception
Public Shared HasException As Boolean
Public Shared ReadOnly Property IsSuccessful() As Boolean
Get
Return HasException = False
End Get
End Property
Public Shared Function Update(pContact As Contact) As UpdateResult
HasException = False
Dim selectStatement =
"SELECT COUNT(ContactId) FROM NorthWindAzureForInserts.dbo.Contacts " &
"WHERE ContactId = @ContactId"
Dim updateStatement =
"UPDATE dbo.Contacts SET FirstName = @FirstName,LastName = @LastName " &
"WHERE ContactId = @ContactId"
Using cn As New SqlConnection With {.ConnectionString = ConnectionString}
Using cmd As New SqlCommand With {.Connection = cn}
cmd.CommandText = selectStatement
Try
cn.Open()
cmd.Parameters.AddWithValue("@ContactId",
pContact.ContactId)
Dim count = CInt(cmd.ExecuteScalar())
If count = 1 Then
cmd.Parameters.Add(New SqlParameter("@FirstName", SqlDbType.NVarChar)).
Value = pContact.FirstName
cmd.Parameters.Add(New SqlParameter("@LastName", SqlDbType.NVarChar)).
Value = pContact.LastName
cmd.Parameters("@ContactId").Value = pContact.ContactId
cmd.CommandText = updateStatement
cmd.ExecuteNonQuery()
Return UpdateResult.Success
Else
Return UpdateResult.NotFound
End If
Catch ex As Exception
HasException = True
LastException = ex
Return UpdateResult.Failed
End Try
End Using
End Using
End Function
End Class
Public Class Contact
Public Property ContactId() As Integer
Public Property FirstName() As String
Public Property LastName() As String
Public ReadOnly Property FullName() As String
Get
Return $"{FirstName} {LastName}"
End Get
End Property
End Class
Public Enum UpdateResult
Success
Failed
NotFound
End Enum
Then call the above with a mocked up of a Contact instance.
Dim contact As New Contact With {
.ContactId = 2,
.FirstName = "Ana",
.LastName = "Trujillo"}
Dim success = DataOperations.Update(contact)
If DataOperations.IsSuccessful AndAlso success = UpdateResult.Success Then
Debug.WriteLine("Contact updated")
ElseIf success = UpdateResult.NotFound Then
Debug.WriteLine("Contact not found")
ElseIf success = UpdateResult.Failed Then
Debug.WriteLine(DataOperations.LastException.Message)
End If
Caveats
- Rather than call the Update method as shown above a better idea is to have a unit test project with several test methods to valid the update method.
- Consider using Entity Framework 6 code first from existing database which in Visual Studio
Here is a taste for Entity Framework 6
Imports System.Data.Entity
Public Class DataOperations
Public Shared Function Update(pContact As Contact) As Boolean
Using context As New NorthWindContext
Dim contact = context.Contacts.Find(pContact.ContactId)
If contact IsNot Nothing Then
contact.FirstName = pContact.FirstName
contact.LastName = pContact.LastName
context.Entry(contact).State = EntityState.Modified
Return context.SaveChanges() = 1
Else
Return False
End If
End Using
End Function
End Class
Called as follows
Dim contact As New Contact With {
.ContactId = 2,
.FirstName = "Ana",
.LastName = "Trujillo"}
Debug.WriteLine(DataOperations.Update(contact))