Dulanga Heshan
Dulanga Heshan

Reputation: 1425

How return string by execute SQL query in dapper

.Execute(sQuery,...) in Dapper returns integer.

string sQuery = "SELECT FirstName FROM Customers WHERE Id = @Id";

How can I implement this to return FirstName?

Upvotes: 5

Views: 13929

Answers (2)

Edward
Edward

Reputation: 29996

For executing query with Asp.Net Core and Dapper, try SqlConnection with Query.

Here is complete code.

using Dapper;

public class CustomersController : Controller
{
    private readonly ApplicationDbContext _context;
    private readonly IConfiguration _configuration;

    public CustomersController(ApplicationDbContext context
        , IConfiguration configuration)
    {
        _context = context;
        _configuration = configuration;
    }

    // GET: Customers/Details/5
    public async Task<IActionResult> Details(int? id)
    {

        using (var connection = new SqlConnection(_configuration.GetConnectionString("DefaultConnection")))
        {
            string sQuery = "SELECT Name FROM Customer WHERE Id = @Id";
            var customer = connection.QueryFirstOrDefault<string>(sQuery, new { Id = id});
        }
        //Rest Code
    }

Upvotes: 5

Nkosi
Nkosi

Reputation: 247163

Execute is an extension method which can be called from any object of type IDbConnection. It can execute a command one or multiple times and return the number of affected rows.

emphasis mine

Execute can't be used for what you are asking.

Use one of the Query* based calls to get desired result

For example

string sQuery = "SELECT FirstName FROM Customers WHERE Id = @Id";

using (var connection = new SqlCeConnection("connection string")) { 
    var firstName = connection.QueryFirstOrDefault<string>(sQuery, new { Id = 1 });

    //...
}

Upvotes: 6

Related Questions