Skip to content

Linq expression builder doesn't support max depth #465

Closed
Khaki976 opened this Issue Feb 24, 2014 · 0 comments

2 participants

@Khaki976

There is a MaxDepth configuration option for CreateMap, but seems the linq expression doesn't respect that. So if I have circular references of an entity and its property, .Project() would result in stackoverflow.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using System.Data.Entity;

namespace AutoMapperExample
{
    class A
    {
        public int AP1 { get; set; }
        public string AP2 { get; set; }
        public virtual B B {get; set;}
    }

    class B
    {
        public B()
        {
            BP2 = new HashSet<A>();
        }
        public int BP1 { get; set; }
        public virtual ICollection<A> BP2 { get; set; }
    }

    class AEntity
    {
        public int AP1 { get; set; }
        public string AP2 { get; set; }
        public virtual BEntity B { get; set; }
    }
    class BEntity
    {
        public BEntity()
        {
            BP2 = new HashSet<AEntity>();
        }
        public int BP1 { get; set; }
        public virtual ICollection<AEntity> BP2 { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Mapper.CreateMap<BEntity, B>().MaxDepth(3);
            Mapper.CreateMap<AEntity, A>().MaxDepth(3);
            Mapper.AssertConfigurationIsValid();

            var be = new BEntity();
            be.BP1 = 3;
            be.BP2.Add(new AEntity() { AP1 = 1, AP2 = "hello", B = be });
            be.BP2.Add(new AEntity() { AP1 = 2, AP2 = "two" , B = be});

            var b = Mapper.Map<BEntity, B>(be);   // this works
            Console.Out.WriteLine("{0} element in b.BP2", b.BP2.Count());

            var belist = new List<BEntity>();
            belist.Add(be);
            IQueryable<BEntity> bei = belist.AsQueryable();
            try
            {
                IQueryable<B> bi = bei.Project().To<B>();  // this cause stackoverflow
            }
            catch (Exception e)
            {
                Console.Out.WriteLine(e.Message);
            }
        }
    }
}
@jbogard jbogard closed this in 1c3db4e Feb 26, 2014
@jbogard jbogard added this to the 3.2.0 milestone Feb 26, 2014
@jbogard jbogard added the Improvement label Apr 15, 2014
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.