Skip to content

Querying LINQ Style

Stelio Kontos edited this page Sep 25, 2023 · 5 revisions

PetaPoco supports a few LINQ inspired query methods. These methods are for commonly used LINQ counterparts that are easily adapted to a traditional database.

Exists<T>

Returns true or false depending on whether the given primary key or statement matches one or more records.

var result = db.Exists<Person>(12); // True or False
result = db.Exists<Person>((object)"JohnSmith"); // Need to cast a string key to object to get the right overload

result = db.Exists<Person>("WHERE Id = @0", 12); // Same as above True or False

result = db.Exists<Person>("WHERE FirstName LIKE '%@0%'", "PetaPoco"); // True or False

Single<T>

Throws an exception if none or more than one record is returned.

var person = db.Single<Person>(12); // The person or an exception
result = db.Single<Person>((object)"JohnSmith"); // Need to cast a string key to object to get the right overload

person = db.Single<Person>("WHERE Id = @0", 12); // Same as above; the person or an exception

person = db.Single<Person>("WHERE FirstName LIKE '%@0%'", "PetaPoco"); // The person or an exception if none or more than one record is returned

SingleOrDefault<T>

Returns default(T), most likely null, if none or more than one record is returned.

var person = db.SingleOrDefault<Person>(12); // The person or NULL
result = db.SingleOrDefault<Person>((object)"JohnSmith"); // Need to cast a string key to object to get the right overload

person = db.SingleOrDefault<Person>("WHERE Id = @0", 12); // Same as above; the person or NUll

person = db.SingleOrDefault<Person>("WHERE FirstName LIKE '%@0%'", "PetaPoco"); // The person or NULL if none or more than one record is returned

First<T>

  • Throws an exception if none is returned.
  • Returns the first record.
var person = db.First<Person>("WHERE Id = @0", 12); // The person, or an exception

person = db.First<Person>("WHERE FirstName LIKE '%@0%'", "PetaPoco"); // The person or an exception if no records are found

FirstOrDefault<T>

  • Returns default(T), most likely null, if no record is returned.
  • Returns the first record.
var person = db.FirstOrDefault<Person>("WHERE Id = @0", 12); // The person or NULL

person = db.FirstOrDefault<Person>("WHERE FirstName LIKE '%@0%'", "PetaPoco"); // The person or NULL if no records are found