开发者

Db4O - Can I save a String?

开发者 https://www.devze.com 2022-12-09 13:40 出处:网络
I have the following code: Assert.IsTrue(Repository.FindAll<string>().Count() == 0); string newString = \"New String\";

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 == n开发者_如何学JAVAull)
        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?


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消