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?
int id = ...
var exists = conn.ExecuteScalar<bool>("select count(1) from Table where Id=@id", new {id});
should work...
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();
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 });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With