I have a rather simplistic API for adding, and then later updating a small table in SQL Server. It will insert (or update, which exhibits the same odd behavior) when I step into
Edited to correct mistakenly calling this an async method - see comments.
You are calling the method BeginExecuteNonQuery which initiates a query, but you must call EndExecuteNonQuery to complete the operation (generally asynchronously). When you debug, this has a chance to complete as you manually step through. When you step over, the connection is disposed prior to completing.
You will need to either update your code to use an Asynchronous Programming Model (APM) pattern or call the synchronous ExecuteNonQuery instead.
BeginExecuteNonQuery()
is an asynchronous method. It will return immediately, before the command is executed. To wait for it to complete, use EndExecuteNonQuery method.
When you call BeginExecuteNonQuery to execute a Transact-SQL statement, you must call EndExecuteNonQuery in order to complete the operation. If the process of executing the command has not yet finished, this method blocks until the operation is complete.
It seems you're looking for synchronous method. If that's the case, simply use
sqlCmd.ExecuteNonQuery();
This one will return only after the command is executed.
If you want to execute the command asynchronously, it's much easier to use the ExecuteNonQueryAsync method.
await sqlCmd.ExecuteNonQueryAsync();
Note that you will have to make your method async
to use await
. You also need .NET 4.5+ to use it.