How to build a Linq Expression for selecting nested objects?

c# entity-framework-core linq

Question

I am using a generic repository to retrieve objects from the database and while lazy loading is not available in EntityFramework Core, sometimes I would need to select related objects.

The repo code looks like this:

public T GetSingle(Expression<Func<T, bool>> predicate, params Expression<Func<T, object>>[] includeProperties)
    {
        IQueryable<T> query = _context.Set<T>();
        foreach (var includeProperty in includeProperties)
        {
            query = query.Include(includeProperty);
        }

        return query.Where(predicate).FirstOrDefault();
    }

and telling it to select a related object is simple:

.GetSingle(id,x=>x.ObjectviaFK)`

I can't wrap my head around building an expression that will allow selecting nested objects (similar to .Include(...).ThenInclude(...) from context), something like .GetSingle(id, x=>Parent,parent=>Grand,grand=>GrandGrand). How do I do this?

1
0
6/27/2017 7:24:16 AM

Accepted Answer

It would seem if you don't want to change your GetSingle you could just put in the correct lambdas to include the nested objects?

`.GetSingle(id, x=>x.Parent, x=>x.Parent.Grand, x=>x.Parent.GrandGrand)
1
6/26/2017 5:50:43 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow