如何存储包含对象的对象

时间:2013-02-13 19:49:32

标签: c# db4o

我有一个小问题 如何存储包含另一个对象的对象? 例如

对象人物

Person { Name, Mother }

其中母亲是同一类人物的另一个对象

希望得到帮助 lczernik

2 个答案:

答案 0 :(得分:1)

class Person
{
    public string Name;
    public Person Mother;
    Person (string name, Person mother)
    {
        Name = name;
        Mother = mother;
    }
}

一样使用它
Person me = new Person("user2069747", new Person("user2069747's mom name", null));
// null was used because you may not know the name of your grand mom;
Console.WriteLine(me.Name) // prints your name
Console.WriteLine(me.Mother.Name) // prints your mom's name

答案 1 :(得分:0)

db4o将自动为您存储整个对象图,但是,由于性能优化,您需要注意以下场景:

  • 对象检索
  • 对象更新

在这两种情况下,db4o都会执行请求某些深度的操作,通过以下配置参数进行设置:

因此,给定以下模型,您可以将对象图存储在一次调用中:

using System;
using Db4objects.Db4o;

namespace Db4oSample
{
    class Person
    {
        public string Name { get; set; }
        public Person Mother { get; set; }

        public override string ToString()
        {
            return Name + (Mother != null ? "(" + Mother + ")" : "");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var grandMother = new Person {Name = "grandma"};
            var mother = new Person {Name = "mother", Mother = grandMother };
            var son = new Person {Name = "son", Mother = mother};

            using(var db = Db4oEmbedded.OpenFile("database.odb")) // Closes the db after storing the object graph
            {
                db.Store(son);
            }

            using(var db = Db4oEmbedded.OpenFile("database.odb"))
            {
                var result = db.Query<Person>(p => p.Name == "son");
                if (result.Count != 1)
                {
                    throw new Exception("Expected 1 Person, got " + result.Count);
                }

                Console.WriteLine(result[0]);
            }
        }
    }
}

希望这有帮助