Exists
This method checks whether matching rows exist in a table.
Code Snippets
The following example checks whether a row exists in the [dbo].[Person] table by primary key.
using (var connection = new SqlConnection(connectionString))
{
var existing = connection.Exists<Person>(10045);
}
A LINQ expression can also be used:
using (var connection = new SqlConnection(connectionString))
{
var existing = connection.Exists<Person>(e =>
e.Name == "Doe" && e.DateOfBirth = DateTime.Parse("2000-01-01"));
}
Targeting a Table
To target a specific table, pass the literal table name.
using (var connection = new SqlConnection(connectionString))
{
var existing = connection.Exists("[dbo].[Person]", 10045);
}
Use QueryGroup or QueryField to build more complex expressions.
using (var connection = new SqlConnection(connectionString))
{
var where = new []
{
new QueryField("Name", "Doe"),
new QueryField("DateOfBirth", DateTime.Parse("2000-01-01"))
};
var existing = connection.Exists("[dbo].[Person]", where);
}
Table Hints
Pass a table hint via the hints argument.
using (var connection = new SqlConnection(connectionString))
{
var existing = connection.Exists<Person>(10045,
hints: "WITH (NOLOCK)");
}
Or use the SqlServerTableHints class.
using (var connection = new SqlConnection(connectionString))
{
var existing = connection.Exists<Person>(10045,
hints: SqlServerTableHints.NoLock);
}