Share via


RelationalDatabaseFacadeExtensions.ExecuteSqlAsync Method

Definition

Executes the given SQL against the database and returns the number of rows affected.

public static System.Threading.Tasks.Task<int> ExecuteSqlAsync (this Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade databaseFacade, FormattableString sql, System.Threading.CancellationToken cancellationToken = default);
static member ExecuteSqlAsync : Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade * FormattableString * System.Threading.CancellationToken -> System.Threading.Tasks.Task<int>
<Extension()>
Public Function ExecuteSqlAsync (databaseFacade As DatabaseFacade, sql As FormattableString, Optional cancellationToken As CancellationToken = Nothing) As Task(Of Integer)

Parameters

databaseFacade
DatabaseFacade

The DatabaseFacade for the context.

sql
FormattableString

The interpolated string representing a SQL query with parameters.

cancellationToken
CancellationToken

A CancellationToken to observe while waiting for the task to complete.

Returns

A task that represents the asynchronous operation. The task result is the number of rows affected.

Exceptions

Remarks

Note that this method does not start a transaction. To use this method with a transaction, first call BeginTransaction(DatabaseFacade, IsolationLevel) or UseTransaction.

Note that the current ExecutionStrategy is not used by this method since the SQL may not be idempotent and does not run in a transaction. An ExecutionStrategy can be used explicitly, making sure to also use a transaction if the SQL is not idempotent.

As with any API that accepts SQL it is important to parameterize any user input to protect against a SQL injection attack. You can include parameter place holders in the SQL query string and then supply parameter values as additional arguments. Any parameter values you supply will automatically be converted to a DbParameter.

See Executing raw SQL commands with EF Core for more information and examples.

Applies to