Json serialization problem - Self referencing loop

1,111 views
Skip to first unread message

Jeremy Holt

unread,
Oct 25, 2012, 6:42:10 PM10/25/12
to rav...@googlegroups.com
Hi - this is probably more to do with my lack of understanding about C# than anything else .....

I have the following classes:

public class Parent
    {
        public Parent()
        {
            Calculated = new Calculator(this);
        }

        public Child Child { get; set; }
        public Calculator Calculated { get; private set; }
    }


    public class Child
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    public class Calculator
    {
        public Calculator(Parent parent)
        {
            Parent = parent;
        }

        public Parent Parent { get; private set; }

        public string Name
        {
            get { return Parent.Child.FirstName + " " + Parent.Child.LastName; }
        }
    }

I can serialize and deserialize Parent correctly by making direct calls to JsonConvert.SerializeObject. 

I can also map Parent using Automapper.

However Raven will not SaveChanges, reporting that Parent.Calculated.Name is null. If I expose Calculator.Parent as a public property I get " Self referencing loop detected". If I make Parent (_parent) a private field of Calculator, it is not getting initialized at the moment that SaveChanges is called, but no Self referencing loop exception.


Is there some way of getting around this? I can force the initialization of Calculator by adding an Init method to both Parent and Calculator (which is what I'm doing at the moment) - but this is very smelly, i.e. in Calculator:

public void Init(Parent parent){
    this._parent = parent;
}

Many thanks in advance
Jeremy

Oren Eini (Ayende Rahien)

unread,
Oct 26, 2012, 2:49:09 AM10/26/12
to rav...@googlegroups.com
[JsonObject(IsReference=true)]
public class Parent

Jeremy Holt

unread,
Oct 26, 2012, 7:32:02 AM10/26/12
to rav...@googlegroups.com
Hi

I tried that, and it works when saving the record, but not when loading, i.e.
var parent = session.Load<Parent>("parents-1")

parent.Calculated is still null

Oren Eini (Ayende Rahien)

unread,
Oct 26, 2012, 7:38:56 AM10/26/12
to rav...@googlegroups.com
Can you create a failing test?

Jeremy Holt

unread,
Oct 27, 2012, 9:34:03 AM10/27/12
to rav...@googlegroups.com

Oren Eini (Ayende Rahien)

unread,
Oct 27, 2012, 2:40:41 PM10/27/12
to rav...@googlegroups.com
The problem is that the Calculator is using a private field, which does NOT get serialized.

If you changed that to a property, it all works.


public Contract Contract { get; set; }

public Calculator(Contract contract)
{
Contract = contract;

Jeremy Holt

unread,
Oct 27, 2012, 2:54:30 PM10/27/12
to rav...@googlegroups.com
Great, thanks. I guess I should have thought of that.
Reply all
Reply to author
Forward
0 new messages