LiteDb class deserialization is not working

443 views Asked by At

I have B class that has a class A as member. The LiteDb store it correctly as I see in LiteDB Studio. "As" collection is also OK. Why is it not right in the deserialization? Class A has a BsonCtor. B also

namespace ConsoleAppTestDeserializatioBug {
    class Program {
        public class A {
            public A() { A_ID = ObjectId.NewObjectId(); }
            [BsonCtor]
            public A(ObjectId id, string name) { A_ID = id; Name = name; }
            [BsonId]
            public ObjectId A_ID { get; set; }
            public string Name { get; set; }
            public const string CollectionName = "As";
        }
        public class B {
            public const string CollectionName = "Bs";
            public B() { B_ID = ObjectId.NewObjectId(); }
            [BsonCtor]
            public B(ObjectId id, int dummy, A a) { B_ID = id; Dummy = dummy; aObj = a;}
            [BsonId]
            public ObjectId B_ID { get; set; }
            public int Dummy { get; set; }
            [BsonRef(A.CollectionName)]
            public A aObj { get; set; }
        }
        private LiteDatabase _LiteDatabase;
        static void Main(string[] args) {
            var p = new Program();
            p.Test();
        }
        private void Test() {
            A a = new A(); // Create my Object
            a.Name = "Name123";
            var initialId = a.A_ID;
            B b = new B();
            b.Dummy = 123;
            b.aObj = a;
                 _LiteDatabase = new LiteDatabase(new ConnectionString(@"C:\Temp\tst1.db") { Connection = ConnectionType.Shared });
            ILiteCollection<A> aas = _LiteDatabase.GetCollection<A>(A.CollectionName);
            aas.Insert(a);
            ILiteCollection<B> bs = _LiteDatabase.GetCollection<B>(B.CollectionName);
            bs.Insert(b);

            // Get in the DB
            var bb = bs.FindAll().ToArray()[0];
            var aa = bb.aObj;
            var aaid = aa.A_ID;
            if (aaid == initialId) { Console.WriteLine("Id is correct");}
            var aname = aa.Name; // aname i s null!!!!! and why
        }
    }
}
1

There are 1 answers

0
swWork On

I found an answer in LiteSB DbRef

I must just add an "include" in my query:

var bb = bs.Include(x => x.aObj).FindAll().ToArray()[0];