C# Apply includes recursively to Query (IncludeWhile)

78 views Asked by At

I'm trying to build dependency graph by grabbing dependencies from EntityFramework. I would like my query to be as efficient as possible, so I would prefer not to pull all of the data.

I have a structure which self references multiple times like so:

public class PTOPlan
{
    public int Id { get; set; }    
    public string Name { get; set; }
    public decimal Allowed { get; set; }
    public decimal Taken { get; set; }
    public PTOPlan DependentPTO { get; set; }
    public PTOPlan RolloverPlan { get; set; }
    public int RolloverPlanId { get; set; }
    public int DependentPTO { get; set; }
    public List<PTOPlanRule> PTOPlanRules { get; set; }    

}

Later on we introduced a more granular way of creating rules, but for legacy purposes we left the old structure in place

public class PTOPlanRule
{
    public int Id { get; set; }
    public int DepartmentId { get; set; }
    public string Name { get; set; }
    public decimal Allowed { get; set; }
    public decimal Taken { get; set; }
    public PTOPlan ParentPTOPlan{ get; set; }
    public PTOPlan DependentPTO { get; set; }
    public PTOPlan RolloverPlan { get; set; }
    public int ParentPTOPlanId { get; set; }
    public int RolloverPlanId { get; set; }
    public int DependentPTO { get; set; }
} 

I need to build a graph of the dependencies. But Some places have a lot of plans and I would prefer to not have to pull the dataset into memory.

I would like the includes to be applied recursively to the query, so they pull all the dependencies. e.g I would like to Include a dependency while the Id exists

public Dictionary<int, List<int>> GetPTOPlanDependencyGraph(List<int> ptoPlanIds)
{
    var rawPlans = context.PTOPlans.Where(x => ptoPlanIds.Contains(x.Id))
        .IncludeWhile(x => x.DependentPTOPlan, x.DependentPTOPlan != null)
        .IncludeWhile(x => x.RolloverPlan, x.RolloverPlan != null)
        .IncludeWhile(x => x.PTOPlanRules.SelectMany(x => x.DependentPTOPlan), x => x.PTOPlanRules.Any())
    
     return this.BuildDependencyGraph(rawPlans);
}

Is there a way to recursively include data, or a way to pull my data without having to grab extra plans?

0

There are 0 answers