Dapper execute returns negative value

The Dapper Execute method returns a negative value if the query execution fails. Let’s explain in detail with examples.

Dapper is a lightweight Object-Relational Mapping (ORM) framework for .NET. It provides a fast and efficient way to retrieve data from a database using SQL queries.

The Execute method in Dapper is used to execute a query that does not return any result set, such as an INSERT, UPDATE, or DELETE statement. It returns the number of affected rows as an integer, with a negative value indicating an error or failure.

Here’s an example of how to use the Execute method:

// Assuming you have a database connection named 'connection'

string sql = "DELETE FROM Users WHERE Id = @UserId";
int userId = 1;

int affectedRows = connection.Execute(sql, new { UserId = userId });

if (affectedRows >= 0)
{
    Console.WriteLine("Deletion successful. Affected rows: " + affectedRows);
}
else
{
    Console.WriteLine("Deletion failed.");
}

In this example, we are using the Execute method to delete a user from the “Users” table. The SQL query uses a parameterized query to specify the “Id” of the user to be deleted. The affectedRows variable will contain the number of affected rows after executing the query.

If the deletion is successful, the value of affectedRows will be greater than or equal to 0, and a success message will be printed. Otherwise, if the query fails or encounters an error, the value of affectedRows will be negative, and a failure message will be printed.

Related Post

Leave a comment