This project is read-only.

ObjectContext Guidelines

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#
// 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);
    }
}

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

' Create an ObjectReader to read all User persistent objects from the first
' database.
Dim objectReader = context1.GetObjectReader(Of User)()

Try
    ' Loop over all user...
    For Each user In objectReader
        ' ... and insert them in the second database.
        context2.PersistChanges(user)
    Next
Finally

End Try

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.

Last edited Nov 24, 2009 at 6:19 PM by davidbrown, version 1

Comments

No comments yet.