ISqlExecutor.ExecuteProcedureAsync(string procedureName, object[] parameters, CancellationToken cancellationToken) Method
.NET Standard 2.x
Asynchronously executes a SQL stored procedure which does not need to return the result set.
Namespace: SnapObjects.Data
Assembly: SnapObjects.Data.dll
Syntax
public Task<int> ExecuteProcedureAsync(string procedureName, object[] parameters, CancellationToken cancellationToken);
Parameters
procedureName
System.String
The name of the SQL stored procedure.
parameters
System.Object[]
The parameters for executing the SQL stored procedure.
One or more objects, containing the parameter direction and values, which correspond to the SQL stored procedure's parameters.
cancellationToken
CancellationToken
A cancellation token that can be used by other objects or threads to receive notice of cancellation.
Returns
Task<int>
Returns a task that represents the asynchronous operation.
Examples
The following code example use this method to asynchronously execute the StoredProcedure. It uses a CancellationTokenSource type parameter to make this operation cancelable.
using System;
using System.Data;
using SnapObjects.Data;
using System.Data.SqlClient;
using System.Threading.Tasks;
using System.Threading;
namespace Appeon.ApiDoc.ISqlExecutorExamples
{
public class ExecuteProcedureAsyncExample
{
private readonly SchoolContext _context;
public ExecuteProcedureAsyncExample(SchoolContext dataContext)
{
// Sets the data context
_context = dataContext;
}
public async Task<int> Example2(CancellationTokenSource cts)
{
// Specifies the procedure to be executed.
// It inserts a person record to database and returns the new PersonID.
string procedureName = "GetDepartmentName";
/* StoredProcedure GetDepartmentName:
CREATE PROCEDURE[dbo].[GetDepartmentName]
@ID int,
@Name nvarchar(50) OUTPUT
AS
SELECT @Name = Name FROM Department
WHERE DepartmentID = @ID
GO
*/
// Sets the parameter values.
// The parameter direction defaults to ParameterDirection.Input,
// so you can omit it.
ParamValue idParam = ParamValue.New<string>("id", "4");
// The parameter 'Name' is Output type.
ParamValue nameParam = ParamValue.Output<string>("name");
int rowAffected = 0;
try
{
// If a task has been cancelled, the call to the
// SqlExecutor.ExecuteProcedureAsync method throws an OperationCanceledException.
rowAffected = await _context.SqlExecutor.ExecuteProcedureAsync(
procedureName, new object[] { idParam, nameParam }, cts.Token);
Console.WriteLine("Department Name: {0}", nameParam.Value);
}
catch (OperationCanceledException e)
{
// The operation was cancelled before completion.
Console.WriteLine(e.Message);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
cts.Dispose();
}
return rowAffected;
/*This code produces the following output:
A task was canceled.
*/
}
}
}
Applies to
.NET Standard
2.x