MaxDepth (Type Adapter Configuration)

Solution for StackOverflowException

Test Classes

public class Source
{
    public int Level { get; set; }
    public IList<Source> Children { get; set; }
    public Source Parent { get; set; }

    public Source(int level)
    {
        Children = new List<Source>();
        Level = level;
    }

    public void AddChild(Source child)
    {
        Children.Add(child);
        child.Parent = this;
    }
}

public class Destination
{
    public int Level { get; set; }
    public IList<Destination> Children { get; set; }
    public Destination Parent { get; set; }
}


Configure

//TypeAdapterConfiguration.cs
public static class TypeAdapterConfiguration
{
    public static void Initialize()
    {
        TypeAdapterConfig<Source, Destination>
            .NewConfig()
            .MaxDepth(3);
    }
}

//Global.asax
protected void Application_Start()
{
    TypeAdapterConfiguration.Initialize();
}


Test Data

public Source GetSource()
{
    var nest = new Source(1);

    nest.AddChild(new Source(2));
    nest.Children[0].AddChild(new Source(3));
    nest.Children[0].AddChild(new Source(3));
    nest.Children[0].Children[1].AddChild(new Source(4));
    nest.Children[0].Children[1].AddChild(new Source(4));
    nest.Children[0].Children[1].AddChild(new Source(4));

    nest.AddChild(new Source(2));
    nest.Children[1].AddChild(new Source(3));

    nest.AddChild(new Source(2));
    nest.Children[2].AddChild(new Source(3));

    return nest;
}


Map

var dest = TypeAdapter.Adapt<Source, Destination>(GetSource());

//result : 
Assert.IsNotNull(dest);
Assert.IsTrue(dest.Children.Count == 3);
Assert.IsTrue(dest.Parent == null);
Assert.IsTrue(dest.Level == 1);


Last edited Apr 15, 2014 at 11:54 AM by timucinkivanc, version 2