All persistent objects that your OpenAccess ORM application creates and uses are stored in a database. Note, that only the values of the persistent fields (data-members) are stored.
In OpenAccess ORM, all of your work with persistent objects is done within the context of an object scope. The object scope represents the database connection and handles the details of the persistent object lifecycle in your application. Therefore, in order to work with persistent objects you first need to establish an object scope. The implementation of the object scope is defined by the IObjectScope interface.
Retrieving the Object Scope
The following code fragment shows how to make a connection to an OpenAccess ORM database and retrieve an IObjectScope instance:
[Visual Basic]
|
Copy Code |
Dim scope As IObjectScope =
Database.Get( "DatabaseConnection1" ).GetObjectScope()
|
[C#]
|
Copy Code |
IObjectScope scope =
Database.Get( "DatabaseConnection1" ).GetObjectScope();
|
The passed ConnectionId is defined in the Configuration File.
Obtaining the IObjectContext from a persistent object
It is possible to obtain the "manager", i.e., the IObjectContext instance responsible for the passed persistence capable object, by using the Database.GetContext() method. This method takes a single parameter, a persistent object, and returns the context of the passed object, which could be either an objectscope or an objectcontainer or null.
The Database.GetContext()method can be used in situations where the scope or container is not passed explicitly.
It is recommended to use this method from a central place in your class hierarchy in order to simplify the code. An example demonstrating the usage of this method is given below:
|
Copy Code |
using OpenAccess;
public abstract MyBaseClass
{
// Central place to obtain the database context, limited here to connected usage.
public IObjectScope Scope
{
get
{
return Database.GetContext(this) as IObjectScope;
}
}
}
[Persistent]
public class Person : MyBaseClass
{
// Usage of the Scope property for demonstration purposes only
IEnumerable AsOldAsMe()
{
// A sample OQL query string
string oqlexpr = "select * from "+this.GetType().FullName+"Extent as p
where p.birthday = $1";
// Will fail if this instance is not persistent yet and this.Scope returns null.
return this.Scope.GetOqlQuery(oqlexpr).Execute(this.birthday);
}
}
|