Search code examples
c#sqldapper

How to use select count() as ... in C#


I'm making a simple login page using a database. So for my queries i'm using Dapper and i'm stuck on following query.

connection.Execute(@"SELECT count(Id) as Id FROM tblMedewerkers 
where Naam = @Naam and Paswoord = @Paswoord",
new{
 Naam = naam,
 Paswoord = paswoord
  }); 

So if the part "count(Id) as Id " returns 1 the login is correct. If it returns 0 it's wrong.

But how do I get the data from "count(Id) as Id" into something to work with?


Solution

  • Execute performs a non-query operation (usually an insert or delete that doesn't select anything). You want a Query method - the most convenient probably being QuerySingle<int>, because you expect exactly one value that is an int.

    int count = connection.QuerySingle<int>(@"SELECT count(Id) as Id FROM tblMedewerkers 
    where Naam = @Naam and Paswoord = @Paswoord",
    new{
     Naam = naam,
     Paswoord = paswoord
      });