Introduction to the ISession

The ISession is the entry point to the database for user code. It exposes the methods to perform basic CRUD operations for objects. To ensure that all resources and connections are properly cleaned up, ensure that each ISession is disposed correctly. The API is kept intentionally small to make it easy to use.

Delete
The delete method accepts the object you wish to delete. It will generate and execute an SQL statement to delete the row from the table with the identifier specified by the object passed to the method.

bool deleted;

using (var session = sessionFactory.OpenSession())
{
    using (var transaction = session.BeginTransaction())
    {
        deleted = session.Delete(customer);

        transaction.Commit();
    }
}

if (!deleted)
{
    // Inform user.
}

Fetch
The fetch method accepts an SqlQuery and returns the matching results in an IList<T>. Since this could result in a large number of objects being returned, it is suggested that Fetch is used to retrieve associated data (e.g. the invoices for a customer, or comments for a blog post) rather than searching.

Note – Objects will be populated based upon the values in the select list which allows you to choose which properties are populated, however take care if you then want to issue an update based upon a partially read object as it could result in data loss (e.g. nulling or zeroing existing values).

using (var session = sessionFactory.OpenSession())
{
    var query = new SqlQuery("SELECT [CustomerId], [Name], [DoB], [StatusId] FROM [Customers]");

    var customers = session.Fetch<Customer>(query); // customers will be an IList<Customer>
}

Insert
The insert method accepts the object you wish to insert into the database. It will generate and execute an SQL statement to insert a row into the table the class is mapped to. If you have used the Identity strategy, the identifier value on the object will be updated. If you are using Assigned, you should specify the identifier before inserting.

using (var session = sessionFactory.OpenSession())
{
    using (var transaction = session.BeginTransaction())
    {
        var customer = new Customer
        {
            DateOfBirth = DateTime.Today,
            Name = "Fred Flintstone",
            Status = CustomerStatus.Active
        };

        session.Insert(customer);

        // customer.Id will now be set to the value generated by the database when the record was inserted.
        transaction.Commit();
    }
}

Paged
The paged method takes an SqlQuery and rewrites it so that you can easily page queries. Paged supports WHERE and ORDER BY clauses when generating the paged query. Since Paged can return a subset of the full result set, it is ideally suited for searching.

Note – As with Fetch, the objects returned will be populated based upon the values in the select criteria.

using (var session = sessionFactory.OpenSession())
{
    var query = new SqlQuery("SELECT [CustomerId], [Name], [DoB], [StatusId] FROM [Customers]");

    var page1 = session.Paged<Customer>(query, page: 1, resultsPerPage: 25);
}

The result object is a PagedResult which has 3 properties.

Page – This is the page number requested.
Results – This is an IList<T> of objects.
ResultsPerPage – This is the number of results requested per page.

Single
The single method is used to retrieve a single result from the database, it accepts either the identifier value (primary key) for the row or an SqlQuery. If supplied with an identifier, it will generate and execute an SQL statement to select the row from the table with the specified identifier. It will return null if no resulting record is found or throw a MicroLiteException if there are multiple matches.

using (var session = sessionFactory.OpenSession())
{
    var customer = session.Single<Customer>(12353);

    if (customer == null)
    {
        // No customer found with id 12353.
    }
}

Update
The update method accepts the object you wish to update the corresponding row for. It will generate and execute an SQL statement to update the row from the table with the identifier specified by the object passed to the method setting the column values to the values on the supplied instance.

using (var session = sessionFactory.OpenSession())
{
    using (var transaction = session.BeginTransaction())
    {
        var customer = session.Single<Customer>(12354);
        customer.Status = CustomerStatus.Inactive;

        session.Update(customer);

        transaction.Commit();
    }
}

This article was written for version 1.2.2 of the MicroLite framework.

Advertisements

One thought on “Introduction to the ISession

  1. Pingback: What are the session interfaces | MicroLite ORM

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s