Skip to content

Create Read Update Delete

Ryan Gates edited this page Jun 28, 2016 · 5 revisions

This wiki page refers to the User class found here.

Inserting a new record

IDatabase db = new Database("connStringName");
User u = new User() 
{
    Email = "[email protected]",
    LastLoggedIn = DateTime.UtcNow
};

db.Insert(u);

This will insert the User object into the users table generating a new identity value. This value will be populated back into the object after the insert statement. For example, the following would be true.

Reading the new record

var user = db.SingleById(u.UserId);
Assert.AreEqual(u.Email, user.Email);

Updating the record

Once I have the object, I can update its properties. After calling the Update method, those changes will be persisted to the database.

var user = db.SingleById(1);
user.Email = "[email protected]";
db.Update(user);

Deleting the record

If I decide I no longer need the record I can delete it in a very similar fashion to Insert and Update. That is by passing the object to the Delete method. Just the primary key value can also be passed to the Delete method, however the generic type parameter will need to be specified.

var user = db.SingleById(1);
db.Delete(user);

or

db.Delete<User>(1);

Upsert the record

This will insert a record if it is new or update an existing record if it already exists. Its existence is determined by its primary key.

IDatabase db = new Database("connStringName");
User u = new User() 
{
    Email = "[email protected]",
    LastLoggedIn = DateTime.UtcNow
};

db.Save(u);