views:

83

answers:

1

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?

+3  A: 

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);
Travis Heseman