Home > other >  How can I stop the recursiveness of my Expression Tree? (C# / EF)
How can I stop the recursiveness of my Expression Tree? (C# / EF)

Time:11-12

I'm trying to get data out of my database using C# and Entity Framework. My problem is that i have a recursive data model called "Template" which has a propperty called "Templates" which is a ICollection of "Template". In my query i have a .Select(PageMappings.PageMapping). PageMapping is an Expression tree. Eventually it goes to an Expresstion tree called "TemplateMapping". This Expression tree is recursive as you can see in the following code.

public static readonly Expression<Func<Data.Entities.Components.Layout.Template, Models.Components.Layout.Template>> TemplateMapping = 
    tp => new Models.Components.Layout.Template()
    {
        Title = tp.Title ?? string.Empty,
        Id = tp.HtmlId ?? string.Empty,
        Name = tp.Name ?? string.Empty,
        Alt = tp.Alt ?? string.Empty,
        //TODO Create mapping for the classes and styles
        Classes = tp.Classes.FormatStringToList(),
        Styles = tp.Styles.FormatStringToList(),

        Segments = (List<Segment>)new List<Segment>()
            .Concat(tp.Templates.AsQueryable().Select(TemplateMapping))
            .Concat(tp.Rows.AsQueryable().Select(RowMapping)).ToList()
    };

Somehow it keeps on calling TemplateMapping inside of TemplateMapping even if there is not a single "Template" inside the ICollection of "Templates".

I tried adding a .Where(x => x.Templates != null). But this makes no diffrence.

How could i add a clause which ends the recursiveness of TemplateMapping when there are no "Template" inside of "Templates"?

CodePudding user response:

Thank you for your suggestions! It made me look at the problem from a diffrent perspective.

I tried mapping it to a diffrent object inside of the query. This worked up untill it got to the recursive part of of the code for "TemplateMapping". I thought this would make the code good and clean. It looked clean, but it didn't work.

In my working version I wait for the data. Afterwhich i map it the way i want it to.

I wont be putting the working code here since its almost 300 lines.

  • Related