Hi,
I am trying to use SqlTransaction object in my vb code for an application to insert vendor info.
The code runs till inserting a transaction and then gives following exception:
"Execute requires the command to have a transaction object when the connection assigned to the command is in a pending local transaction. The Transaction property of the command has not been initialized."
Any idea what's wrong with this? The code is as follows :
Code:Public Shared Function AddVendor(ByVal vendor As Vendor) As Integer Dim connection As SqlConnection = PayablesDB.GetConnection Dim vendorTransaction As SqlTransaction connection.Open() vendorTransaction = connection.BeginTransaction Dim insertStatement As String _ = "INSERT Vendors " _ & "(Name, Address1, Address2, City, State, ZipCode, Phone, " _ & "ContactFName, ContactLName, DefaultTermsID, DefaultAccountNo) " _ & "VALUES (@Name, @Address1, @Address2, @City, @State, " _ & "@ZipCode, @Phone, @ContactFName, @ContactLName, " _ & "@DefaultTermsID, @DefaultAccountNo)" Dim insertCommand As New SqlCommand(insertStatement, connection) insertCommand.Connection = connection insertCommand.Transaction = vendorTransaction insertCommand.Parameters.AddWithValue("@Name", vendor.Name) insertCommand.Parameters.AddWithValue("@Address1", vendor.Address1) If vendor.Address2 = "" Then insertCommand.Parameters.AddWithValue("@Address2", DBNull.Value) Else insertCommand.Parameters.AddWithValue("@Address2", vendor.Address2) End If insertCommand.Parameters.AddWithValue("@City", vendor.City) insertCommand.Parameters.AddWithValue("@State", vendor.State) insertCommand.Parameters.AddWithValue("@ZipCode", vendor.ZipCode) If vendor.Phone = "" Then insertCommand.Parameters.AddWithValue("@Phone", DBNull.Value) Else insertCommand.Parameters.AddWithValue("@Phone", vendor.Phone) End If If vendor.ContactFName = "" Then insertCommand.Parameters.AddWithValue("@ContactFName", DBNull.Value) Else insertCommand.Parameters.AddWithValue("@ContactFName", vendor.ContactFName) End If If vendor.ContactLName = "" Then insertCommand.Parameters.AddWithValue("@ContactLName", DBNull.Value) Else insertCommand.Parameters.AddWithValue("@ContactLName", vendor.ContactLName) End If insertCommand.Parameters.AddWithValue("@DefaultTermsID", vendor.DefaultTermsID) insertCommand.Parameters.AddWithValue("@DefaultAccountNo", vendor.DefaultAccountNo) Try insertCommand.Transaction = vendorTransaction insertCommand.Connection = connection insertCommand.ExecuteNonQuery() Dim selectStatement As String _ = "SELECT IDENT_CURRENT('Vendors') FROM Vendors" Dim selectCommand As New SqlCommand(selectStatement, connection) Dim vendorID As Integer = CInt(selectCommand.ExecuteScalar) Return vendorID vendorTransaction.Commit() Catch ex As SqlException vendorTransaction.Rollback() Throw ex Finally connection.Close() End Try End Function





Reply With Quote
