.Execute(sQuery,...) in Dapper returns integer.
string sQuery = "SELECT FirstName FROM Customers WHERE Id = @Id";
How can I implement this to return FirstName?
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 });
//...
}
Execute, but that's the wrong one and doesn't do what you want; the method you want - provided by dapper - is: QueryFirstOrDefault. The <string> tells it what a row should look like. Other methods starting with Query... exist for different scenarios. In your case, since you're probably expecting zero or one matches, this is a "first or default" scenario.Execute is for when you are performing something like an insert or update and aren't expecting a result grid. A result grid from a select statement is where the Query... part comes in: you are issuing a query.SqlCeConnection or QueryFirstOrDefault?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
}
Queryto get desired result