-
Notifications
You must be signed in to change notification settings - Fork 41
Basic ObjectDB Usecases
Lets expect you already know how to get IObjectDBTransaction
. Object database is different from sql, or document databases. Basically instead of tables or indexes you can use IDictionary<,>
, now you need to know how to get to such dictionary, for that ObjectDB has singletons. Let's say we want to have Table with Persons with Name and Age fields addressable by some string id.
public class Person
{
public string Name { get; set; }
public uint Age { get; set; }
}
We will store it in singleton object named Root:
public class Root
{
public IDictionary<string,Person> People { get; set; }
}
And now how to create first "row":
using(IObjectDBTransaction tr = db.StartWritingTransaction().Result)
{
// create Root object if does not exist or just load it from DB if already exists
var root=tr.Singleton<Root>();
// create key id1 (it can be anything it is just sample) with some content
root.People["id1"] = new Person { Name = "Boris", Age = 37 };
// store and commit Root object, item in Dictionary, and one person
tr.commit();
}
How to read our person (note that read only transactions are not async because they never block):
using(IObjectDBTransaction tr = db.StartReadOnlyTransaction())
{
var root=tr.Singleton<Root>();
// Gets object id and materializes Person
var person = root.People["id1"];
// do whatever you want with person object here
}
Now how to update age of our person:
using(IObjectDBTransaction tr = db.StartWritingTransaction().Result)
{
var root=tr.Singleton<Root>();
var person = root.People["id1"];
person.Age++;
// Now we have to mark person object as modified, for speed reasons this is not automatic
// Without next line change would be lost
tr.Store(person);
// Store person and commit all changes
tr.Commit();
}
Now we would like to delete our person:
using(IObjectDBTransaction tr = db.StartWritingTransaction().Result)
{
var root=tr.Singleton<Root>();
var person = root.People["id1"];
// next lines you can do in any order you want, but you should not forgot to delete Person or it would be storage leak
tr.Delete(person);
root.People.Remove("id1");
tr.Commit();
}
Now more detailed description why person needs to be Delete
manually in Dictionary itself in value is stored not object itself but just its Object id (ulong
). You can store this object in more Dictionaries and it will preserve object identity, you can simulate Indexes by additional Dictionaries and you know that actual content of Person is stored just once. If you update person fields you don't need to update Dictionaries because updating object does not change its Object id.