Skip to content

Query Single Object

schotime edited this page Apr 26, 2012 · 4 revisions

Selecting an object from the database can be done in a few different ways.

By Id

The easiest way to load an object from the database is by passing the primary key to the SingleById<T>() method.

User u = db.SingleById<User>(3);

Via SQL

Below you can see that only the where is specified. If you don't explicitly supply the select clause it will be automatically generated for you and the where will then be appended.

User u = db.Single<User>("where emailaddress = @0", "[email protected]");
or
User u = db.Single<User>("select u.* from users u where emailaddress = @0", "[email protected]");

Both these methods have a 'OrDefault' method if you are unsure that the object will exist. If it doesn't exist and you don't use the 'OrDefault' override it will throw an exception.

There are also First<T> and FirstOfDefault<T> which will not throw an exception if more than 1 record is returned.