Last Updated: February 25, 2016
·
3.433K
· sergiocosta

Serializing circular references in MongoDb

To serialize an object containing circular references to mongo, you need to set it to ignore the reference, and then initialize it during deserialization:

    [Test]
    public void CanSerializeCircularReferences()
    {
        var parent = new Parent();
        parent.Name = "Parent 1";
        parent.AddChild(new Child() { Name = "Child 1" });
        parent.AddChild(new Child() { Name = "Child 2" });

        var repository = new MongoRepository<Parent>("mongodb://localhost/tests");
        repository.Add(parent);
        var parent2 = repository.GetSingle(p => p.Name == "Parent 1");
        Assert.That(parent2, Is.Not.Null);
        Assert.That(parent2.Children[0].Father,Is.EqualTo(parent2));
    }

public class Parent : Entity, ISupportInitialize
{
    private List<Child> children = new List<Child>();
    public string Name { get; set; }
    public List<Child> Children
    {
        get { return children; }
        set { children = value; }
    }

    public void AddChild(Child toAdd)
    {
        Children.Add(toAdd);
        toAdd.Father = this;
    }

    public void BeginInit()
    {
        return;
    }

    public void EndInit()
    {
        this.Children.ForEach(child => child.Father=this);
    }
}

public class Child
{
    public string Name { get; set; }
    [BsonIgnore]
    public Parent Father { get; set; }
}