Skip to content

Querying LINQ Style

Wade Baglin edited this page Jun 26, 2017 · 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.Exist<Person>("WHERE Id = @0", 12); // Same as above True or False

    result = db.Exist<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

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

    preson = 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.Single<Person>(12); // The person or NULL

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

    preson = db.Single<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>(12); // The person or an exception

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

    preson = 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>(12); // The person or NULL

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

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