Working with Persistent Objects

Welcome back! This lesson gives an overview of how to work with persistent objects in your application. You will learn how to load an ObjectSet, an ObjectReader or a single persistent object from the database. It shows also how to save the changes on persistent objects in the database. Let's start!

Loading an ObjectSet

An ObjectSet is a class that holds a list of persistent objects. It's very simple to load an ObjectSet from the database. The following sample shows how to load an ObjectSet containing all News persistent objects that are located in the database.

We are using the ObjectContext instance created in the Lesson 1 to load the list of persistent objects:

C#
// Get all news from the database. Store them in an ObjectSet.
// An ObjectSet is similar to the DataSet in .NET.
// You may also limit the results by specifying conditions.
ObjectSet<News> os = context.GetObjectSet<News>();

VB.NET
' Get all news from the database. Store them in an ObjectSet.
' An ObjectSet is similar to the DataSet in .NET.
' You may also limit the results by specifying conditions.
Dim os As ObjectSet(Of News) = context.GetObjectSet(Of News)()

The ObjectSet holds now all database's News persistent objects. You may also specify conditions to filter the result of the query. Later in this lesson conditions are used, to load a single object.

Next we loop over all loaded persistent objects and output the text in the Title property to the console window.

C#
// Loop over all objects from the database.
foreach (News n in os)
{
    // Output the title.
    Console.WriteLine("Title: " + n.Title);
}

VB.NET
'Loop over all objects from the database.
For Each n As News In os
    ' Output the title.
    Console.WriteLine("Title: " + n.Title)
Next

Saving the changes on a persistent object

The next step takes us to change a property of one News persistent object and save the changes to the database. We get the first persistent object from the current ObjectSet instance and alter the Title property. To make sure that the update is done in an atomic fashion we create a transaction before saving the changes and commit that transaction afterwards.

C#
// Get the first persistent object.
News news = os[0];
// Change the title.
news.Title = "This is a test";

// Save the changes. We create also a transaction.
context.StartTransaction();
context.PersistChanges(news);
context.Commit();

VB.NET
' Get the first persistent object.
Dim news As News = os.Item(0)
' Change the title.
news.Title = "This is a test"

' Save the changes. We create also a transaction.
context.StartTransaction()
context.PersistChanges(Of News)(news)
context.Commit()

When working with transactions you should always do exception handling to roll-back the transaction, if an exception occured. The following sample code shows how the update has been modified to handle exceptions.

C#
// Save the changes. We create also a transaction.
context.StartTransaction();
try
{
    context.PersistChanges(news);
    context.Commit();
}
catch (Exception ex)
{
    // Roll the update back.
    context.Rollback();
    Console.WriteLine("We got an exception: " + ex.Message);
}

VB.NET
' Save the changes. We create also a transaction.
context.StartTransaction()
Try
    context.PersistChanges(Of News)(news)
    context.Commit()
Catch ex As Exception
    ' Roll the update back.
    context.Rollback()
    Console.WriteLine("We got an exception: " + ex.Message)
End Try

Loading a single persistent object with conditions

It's now time to load a single persistent object from the database. We specify conditions to get only one single object from the database. If the conditions would return more then one persistent object the first one is returned. When specifying conditions we use the property names of the persistent objects. Not the column names. If the column in the database is named E_MAIL and the property EMail, we use EMail. Conditions are storage independent.

In this sample we return all News persistent objects with the ID property set to 1:

C#
// Get the news persistent with the ID 1. We use here the same
// name as the property of the persistent object has. Not the 
// name of the columns.
News news1 = context.GetObject<News>("ID = {0}", 1);

VB.NET
' Get the news persistent with the ID 1. We use here the same
' name as the property of the persistent object has. Not the 
' name of the columns.
Dim news1 As News = context.GetObject(Of News)("ID = {0}", 1)

Working with conditions is like working with string.Format. To specify the first condition's value just enter {0}, for the second {1}, and so on... All values specified in that way are transformed to database parameters when creating the final SQL query that is executed on the database.

Using the ObjectReader

The ObjectReader is a cursor on the database. The class allows to loop over all persistent objects returned by a request, but have always only one item in memory. Provides a way of reading a forward-only stream of objects from a data source.

The following sample shows how to get all News persistent objects from the database by using an ObjectReader. You may specify also here conditions to filter the result.

C#
// Create an ObjectReader to get all news object from the
// database. An ObjectReader is similar to the DataReader of .NET
// You may also limit the results by specifing conditions.
using (ObjectReader<News> reader = context.GetObjectReader<News>())
{
    // Loop over all items in the ObjectReader.
    foreach (News n in reader)
    {
        Console.WriteLine("Title: " + n.Title);
    }
}

VB.NET
' Create an ObjectReader to get all news object from the
' database. An ObjectReader is similar to the DataReader of .NET
' You may also limit the results by specifing conditions.
Using reader As ObjectReader(Of News) = context.GetObjectReader(Of News)()

    ' Loop over all items in the ObjectReader.
    For Each n As News In reader
        Console.WriteLine("Title: " + n.Title)
    Next

End Using

It's important that the ObjectReader instance is immediately closed after having loaded the required persistent objects. The ObjectReader holds an open connection to the database until you call Close or Dispose. By encapsulating the ObjectReader in a using block you make sure that the instance is closed and disposed immediately after leaving the block.

That's it! We loaded and saved persistent objects. You know now how to work with persistent objects. Please go to the Advanced Tutorial to see other benefits of the Opf3 Framework.

Last edited Nov 24, 2009 at 3:42 AM by davidbrown, version 1

Comments

No comments yet.