This website is intended as archive for old content and forums.
Please visit http://opf3.codeplex.com for the project's new website.

Guideline: Multiple ObjectContext instances

This guideline shows how to use multiple ObjectContext instances in your application. The example demonstrates how to copy persistent objects from one database to another. They are read from the first database using an ObjectReader (client side database cursor) and stored to the second database.

C#  VB.NET  
// Create the two instance of the ObjectContexts. The first instance connects to
// the first database and the second to the second one.
ObjectContext context1 = new ObjectContext(new AccessStorage("C:\\", "db1.mdb"));
ObjectContext context2 = new ObjectContext(new AccessStorage("C:\\", "db2.mdb"));

// Create an ObjectReader to read all User persistent objects from the first
// database.
using (ObjectReader<User> or = context1.GetObjectReader<User>())
{
    // Loop over all user...
    foreach(User user in or)
    {
        // ... and insert them in the second database.
        context2.PersistChanges(user);
    }
}

The User persistent objects do not implement the ISelfContainingObject interface. This means that the state of the persistent object is stored in the ObjectContext instance used to load/save/delete the persistent object and not in the persistent object itself. When saving the persistent with the second ObjectContext it seems to that class that the object hasn't been saved (it does not know anything about the state, since only the first ObjectContext manages the state) and it is therefore inserted.

If you are working with more then one instance of the ObjectContext in your application and the different instances connect to the same database your persistent objects should implement the ISelfContainingObject. This interface delegates the state and concurrency management to the persistent object instance itself (not the ObjectContext instance handles the state, but the persistent instance itself). It's very easy to implement the interface. For further information see the documentation of that interface or the guideline on webservices and .NET remoting.