5

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

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

How can I implement this to return FirstName?

1
  • 1
    use Query to get desired result Commented Aug 19, 2018 at 19:51

2 Answers 2

6

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 });

    //...
}
Sign up to request clarification or add additional context in comments.

5 Comments

i'm new to .net core can't implement this by using dapper
then with out execute method can't implement this by using dapper
@DulangaHeshan dapper provides many extension methods; one of those is 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.
@DulangaHeshan to be more specific: 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.
@DulangaHeshan What do you mean by can't implement this by using dapper? Do you mean there is no SqlCeConnection or QueryFirstOrDefault?
5

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
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.