1

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

对象人

Person { Name, Mother }

其中 Mother 是同一类 Person 的另一个 Object

谢谢你的帮助 lczernik

4

2 回答 2

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
于 2013-02-13T20:01:25.467 回答
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]);
            }
        }
    }
}

希望这可以帮助

于 2013-02-14T11:52:40.833 回答