I'm trying to build a nested query using Linq/LinqKit. In theory this seems to be easy. But I am stuck with the practical part.
In my database I have a table which has a self-reference to its parent. In my linq-query I now want to select all parents of a given element (and the parents of this one and so on).
In my code I have the following expression in partial class of MyTable
:
public static Expression<Func<MyTable, IEnumerable<MyTable>>> Parents => (entity) => entity.ParentId != null ? new[]{entity.ParentEntity}.Union(Parents.Invoke(entity.ParentEntity) : new MyEntity[]{};
which should select the parent of a given entity and those parents when the ParentId
is set.
The query itself (simplified):
dbContext
.MyTable
.AsExpandable()
.Where(x => x.Id == myId)
.Select(x => new
{
Parents = MyTable.Parents.Invoke(x, dbContext)
});
Running this code ends up in an StackOverflowException
as the stop-condition is not hit and therefore the Parents
-call is nested endlessly until the stack is full.
Any ideas how this can be done or is this not possible? Or is there an other way for fetching nested data using Linq
/LinqKit
within one query?
I already tried passing the context to the expression in order to create a sub-query (also not working):
public static Expression<Func<MyTable, MyContext, IEnumerable<MyTable>>> Parents => (entity, dbContext) => entity.ParentId != null ? new[]{entity.ParentEntity}.Union(Parents.Invoke(dbContext.MyTable.FirstOrDefault(x => x.Id == entity.ParentId), dbContext) : new MyEntity[]{};