ObjectSpaces
Following the introduction to Whidbey article, this blog will feature some new, more advanced features and technologies in Whidbey.
The first technology to look at, and be prepared for, is ObjectSpaces. ObjectSpaces allow you to map your database tables to actual objects you can create and manipulate in your code. Yes, no more scrappy SQL statements :) But ORMs for .NET aren’t new. There are many implementations out there already, but ObjectSpaces is Microsoft’s first step into ORM (Object-Relational Mapping) and as you’ll expect from Microsoft, it’s clean in its design, easy to use, and simple to deploy.
So how does it work? Whereas before, where you’d create a database and some tables, and then use a DataReader or a DataSet to work with results from a SQL statement, using ObjectSpaces, you define mappings between your tables and a class you’ve created in your application which represents the same structure. And once you’ve created an instance of your class, you can tell ObjectSpaces to watch your instance, and update the database accordingly.
Let’s look in this in action. We’re going to create a very simple Zoo, to which we can add some animals and use a simple XML file as our data source.
The first step in any application where we wish to use ObjectSpaces is to write a class to represent any persistent objects we wish to use. In our case, we’ll have a class Animal which has the properties Species, Age, and Weight:
Our class needs to be abstract, as later we will be creating a specialisation of the object to use with the ORM. In this way, we can “override” some key methods in the class, such as the constructor, and ToString():
using System;
using Microsoft.ObjectSpaces;
namespace ZooSystem {
///
Notice the [UniqueId] attribute: this makes the ORM treat our ID property like a primary key.
Once our class has been defined, we need to define the mappings between our data source and our class. Microsoft provide many examples of how to do this with traditional DBMS’s, so I thought it would be advantageous to show how easy it is to work with an XML file store. For this, we only need to tell ObjectSpace’s where to store our XML file:
This can be saved in any file as long as our application can later access it at runtime. We’ll save it as map.xml as per Microsoft literature.
And that’s the setup complete. As I say, it is a little more involved for mapping direct to a DBMS (like SQL Server) however there are numerous articles regarding this.
Let’s move into implementing our Zoo using ObjectSpaces. To begin, we need to create an ObjectSpace referencing our mapping file, map.xml, which is taken as an argument in case its location later changes:
using System;
using Microsoft.ObjectSpaces;
namespace ZooSystem {
public class Zoo {
IObjectSpace objectSpace;
public Zoo(string mapFile) {
try {
// Setup instance of an ObjectSpace with our mapping file.
objectSpace = ObjectSpaceFactory.CreateObjectSpace(mapFile);
}
catch (Exception exception) {
Console.WriteLine(exception);
}
}
We can now start the fun stuff :) To create a new Animal for our Zoo, we can let ObjectSpaces handle the interaction with the database for us:
public void addAnimal(int ID,
string Species,
string Age,
string Weight)
{
Animal animal = null;
try {
animal = (Animal) objectSpace.CreateObject(typeof(Animal),
ID, Age, Weight);
// Commit the changes to the database
objectSpace.BeginTransaction();
objectSpace.Update(animal);
objectSpace.CommitTransaction();
}
catch(Exception exception) {
Console.WriteLine(exception);
if(animal != null) {
objectSpace.RollbackTransaction();
}
}
}
Notice the key points here. We create our object through the ObjectSpace specifying the abstract type we created earlier. After its creation, we can then begin a transaction. A transaction means that if an error occurs during our commitments to the database, we can rollback all changes we made during the transaction. In the code, this is achieved by catching any errors (say, we duplicated an ID) and then using RollBackTransaction to perform a rollback.
Let’s now allow for a change in a variable in an object, this time, to change the weight of an animal in our zoo. Before, this would mean an Update SQL command: not so with ObjectSpaces:
public void updateWeight(int ID, string newWeight) {
Animal animal = null;
string findFilter = "ID="+ID;
animal = (Animal)objectSpace.GetObject(typeof(Animal), findFilter);
try {
objectSpace.BeginTransaction();
animal.Weight = newWeight;
// Commit to DB
objectSpace.UpdateAll();
objectSpace.CommitTransaction();
}
catch(Exception exception) {
objectSpace.RollbackTransaction();
}
}
We can see how easy it is to find objects. We use a filter, which often resembles the WHERE clause of a SQL Select statement:
string findFilter = "ID="+ID;
animal = (Animal)objectSpace.GetObject(typeof(Animal), findFilter);
We could also return collections of animals if we so wished:
reader = objectSpace.GetObjectReader(new ObjectQuery(typeof(Animal), "Species = 'Penguin'", ""));
foreach (Animal animal in reader)
{
Console.WriteLine(animal.ToString());
}
Deleting objects is also performed in a similar fashion. As long as we enclose our modifications within a Begin and a Commit Transaction, our database will be updated accordingly:
public void deleteAnimal(int ID) {
Animal animal = null;
string filter = "ID='+ID;
try {
animal = (Animal) objectSpace.GetObject(typeof(Animal), filter);
if(animal != null) {
objectSpace.DeleteObject(animal);
}
// Commit the changes
objectSpace.BeginTransaction();
objectSpace.Update(animal);
objectSpace.CommitTransaction();
}
Stay tuned for other Whidbey topics!






Nice stuff.
March 4th, 2004 at 8:47 am
Cool… First I’ve heard of this technology.
March 5th, 2004 at 9:33 am
I had a proper look at ObjectSpaces, finally, last night. Very exciting! Makes my geek juices flow!
But there are a couple of things though:
1. Quality of SQL
If the SQL is, basically, crap, then it’s not going to work very well. Possibly, if when using ObjectSpaces, it creates SPs (when using MSSQL 200/Yukon) and you can tweak them, then it might not be too important. But then again, it does kinda defy the point of it.
2. Other DataSources
Obviously, engineering ObjectSpaces to work best with their own RDBMS’ is the smarter thing to do. But making it only available to MSSQL 2000/Yukon could be potentially harmful, even if they added Access. In my work, we opted for MySQL. There isn’t much of a performance increase in using MSSQL to justify the outlay for it, and when upgrading to ASP.NET Whidbey and not having the option to use ObjectSpaces would make me cry myself to sleep! Not only ASP.NET though, internally, we’ve written a lot of apps that use MySQL as its datasource and would have a heavy impact. More crying myself to sleep!
3. Performance Overhead
I started life writing code as a web developer (unless you old 680×0 assembly and AMOS on my lovely Amiga!) and performance is always the first consideration (moving to Windows development was strange on this aspect, but it proved hand, especially PDA development!). If the overhead added by using ObjectSpaces is too much, then it’s not going to be a viable option for web development (reading those XML files can’t be resource friendly!).
That’s about it really… bear in mind that I haven’t actually used ObjectSpaces yet, so my comments might be total crap, and also that ObjectSpaces is far from complete.
:)
March 5th, 2004 at 6:23 pm
You’re absolutely right in many cases dhtmlgod :)
Microsoft’s Whidbey release only supports Microsoft databases, and at present Microsoft have no plans to support other database vendors, though have developed the technology to open it up in the future. Read Andrew Conrad’s unofficial-official position on this.
Microsoft themselves state in their literature for ObjectSpaces, use them if “Raw performance is not your main goal”. That said, overheads of producing your own business object “mappings” will narrow the performance gap too. I’ve used ObjectSpaces in Whidbey, and there is a definite pause when streaming very large data sets with the ObjectReader vs. SqlDataReader…
Microsoft have entered this field rather late in my mind…if they’d had this available when .NET v.1 shipped, it would be something to get excited about. But its all here already, tested, examined, and available. Try Entity Broker, or Paul Wilsons ORMApper which is based on the ObjectSpaces syntax and supports MySQL.
March 6th, 2004 at 8:32 am
You seem to be using a really really old preview version of ObjectSpaces, since the Whidbey preview version is different in many cases from your examples. I recall there was another preview back a few years ago, and there are still a few articles on the net based on it. Check out this article for the current syntax and downloadable sample that will run under Whidbey: http://authors.aspalliance.com/paulwilson/articles/?id=21.
March 19th, 2004 at 1:49 pm
I hacked the examples from what we had at University…apologies if it is no longer current…one of the perils of previewing pre-release technologies I guess :)
The concepts are still relevant however, but I will get on to updating the code. Thanks for the pointer.
March 19th, 2004 at 6:47 pm
This is all great and wonderful but, System.Data.ObjectSpaces DLL is nowhere to be found… Does anyone know where I can get it from?..
December 12th, 2007 at 4:53 am