我有以下代码:

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

但它失败了。我想这与我正在保存字符串这一事实有关。

我的Save()代码是这样的:

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

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

我的持久课程应该有什么特别之处吗?或者我可以用db4o保存几乎任何东西?

有帮助吗?

解决方案

据我所知,平台基元,即使它们可能是引用类型(如System.String),也只会在实例是另一个对象的子项(即在字段中引用)然后该对象时存储被储存了。因此,在C#或Java中的基元上调用Store()将不会保存它。基本上,您需要创建一个实体来引用您的字符串以保存它们;与为了将字符串保存到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);

编辑: 或者更好

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);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top