Question

I have the following code:

 Assert.IsTrue(Repository.FindAll<string>().Count() == 0);
 string newString = "New String";
 Repository.Save(newString);
 Assert.IsTrue(Repository.FindAll<string>().Count() == 1);

But it is failing. I suppose it has something to do with the fact that I'm saving a string.

My Save() code is this:

  public void Save<T>(T obj)
  {
     if (obj == null)
        throw new ArgumentNullException("obj not allowed to be null");

     Db.Store(obj);
     Db.Commit();
  }

Should my persistent classes have something special? Or I can just save pretty much anything with db4o?

Was it helpful?

Solution

As far as I know, platform primitives, even though they may be reference types (like System.String), will only be stored if an instance is a child of another object (i.e. referenced in a field) and then that object is stored. Therefore, calling Store() on a primitive in C# or Java will not save it. Basically, you'll need to create an entity to reference your strings in order to save them; much the same way as you'd need to create a table in order to save strings to an RDBMS.

public class StringEntity
{
   private readonly string value;

   public StringEntity(string value)
      : base()
   {
      this.value = value;
   }
}

...

Assert.IsTrue(Repository.FindAll<StringEntity>().Count() == 0);
Repository.Save(new StringEntity("New String"));
Assert.IsTrue(Repository.FindAll<StringEntity>().Count() == 1);

EDIT: or better yet

public class Primitive<T>
{
   private readonly T value;

   public Primitive(T value)
      : base()
   {
      this.value = value;
   }
}

...

Assert.IsTrue(Repository.FindAll<Primitive<string>>().Count() == 0);
Repository.Save(new Primitive<string>("New String"));
Assert.IsTrue(Repository.FindAll<Primitive<string>>().Count() == 1);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top