Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if record exists with Dapper ORM

Tags:

dapper

What is the simplest way to check if record exists using the Dapper ORM?

Do I really need to define POCO objects for a query where I only want to check if a record exists?

like image 445
webworm Avatar asked Aug 17 '16 21:08

webworm


3 Answers

int id = ...
var exists = conn.ExecuteScalar<bool>("select count(1) from Table where Id=@id", new {id});

should work...

like image 72
Marc Gravell Avatar answered Nov 16 '22 15:11

Marc Gravell


I think this may have a tad less overhead as there's no function call or data type conversions:

int id = ...
var exists = connection.Query<object>(
    "SELECT 1 WHERE EXISTS (SELECT 1 FROM MyTable WHERE ID = @id)", new { id })
    .Any();
like image 43
Kevin Finck Avatar answered Nov 16 '22 16:11

Kevin Finck


const string sql = "SELECT CAST(CASE WHEN EXISTS (SELECT 1 FROM MyTable WHERE Id = @Id) THEN 1 ELSE 0 END as BIT)";
bool exists = db.ExecuteScalar<bool>(sql, new { Id = 123 });
like image 6
Janeks Malinovskis Avatar answered Nov 16 '22 14:11

Janeks Malinovskis