using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using Db4objects.Db4o; using Db4objects.Db4o.Linq; namespace Db4OSeries { internal class Program { private static void Main(string[] args) { File.Delete("database.db4o"); using (var db = StartDataBase()) { EqualityAssumtion(db); } using (var db = StartDataBase()) { EqualityAssumption(db); } DontCrossContainerBoundaries(); Console.ReadKey(); } private static void DontCrossContainerBoundaries() { File.Delete("database.db4o"); var simpleObject = new SimpleObject("Joe"); using (IObjectContainer db = StartDataBase()) { db.Store(simpleObject); } using (IObjectContainer db = StartDataBase()) { simpleObject.Content = "JoeUpdated"; db.Store(simpleObject); var objInDB = (from SimpleObject o in db select o); // So, it should be only one, since db4o tracks by references, right? // But it will fail. Because the object-container track the objects. // And since we have two object-containers here, it will create a copy!! AssertEquals(1, objInDB.Count()); } } private static void EqualityAssumption(IObjectContainer db) { var theObjectFromTheDB = (from SimpleObject o in db select o).First(); theObjectFromTheDB.Content = "changed-content"; var theObjectFromTheDBSecondTime = (from SimpleObject o in db select o).First(); AssertEquals("changed-content", theObjectFromTheDBSecondTime.Content); AssertTrue(ReferenceEquals(theObjectFromTheDB, theObjectFromTheDBSecondTime)); } private static void EqualityAssumtion(IObjectContainer db) { var obj1 = new SimpleObject("Content of Obj1"); db.Store(obj1); var theObjectFromTheDB = (from SimpleObject o in db select o).Single(); var copyButEqual = new SimpleObject(theObjectFromTheDB); AssertEquals(theObjectFromTheDB, copyButEqual); db.Store(copyButEqual); var objInDB = (from SimpleObject o in db select o); // If db4o tracks by equality it would only store one instance AssertEquals(1, objInDB.Count()); } private static void AssertEquals(object expected, object actualValue) { if (!expected.Equals(actualValue)) { Console.Out.WriteLine( string.Format("ASSERTION FAILED: object are not equals. Expected={0} but got={1}", expected, actualValue)); } } private static void AssertTrue(bool isTrue) { if (!isTrue) { Console.Out.WriteLine("ASSERTION FAILED: expected true"); } } private static IEmbeddedObjectContainer StartDataBase() { return Db4oEmbedded.OpenFile(Db4oEmbedded.NewConfiguration(), "database.db4o"); } } }