Search code examples
linq

How to add include to LINQ conditionally


I want to separate the query from this:

var models = await _p.DbContext.Instance.Set<Journal>()
                .Include(x => x.AddedBy)
                .Include(x => x.Transactions)
                .ThenInclude(x => x.FinancialAccount)
                .Where(predicate)
                .ToListAsync();

To this:

 var cmd = _p.DbContext.Instance.Set<Journal>();
                cmd.Include(x => x.AddedBy);
                cmd.Where(predicate);
                cmd.Take(vm.PagingInfo.Size);

                if (vm.ReportId > 0)
                    cmd.Include(x => x.Transactions).ThenInclude(t => t.FinancialAccount);

                var models = await cmd.ToListAsync();

It is working, but the includes, where clause not working.


Solution

  • The method IQueryable.Include don't modify the query, but return a new query. You need to store the return, like :

    var cmd = _p.DbContext.Instance.Set<Journal>().AsQueryable();
    cmd = cmd.Include(x => x.AddedBy);
    cmd = cmd.Where(predicate);
    cmd = cmd.Take(vm.PagingInfo.Size);
    if (vm.ReportId > 0)
        cmd = cmd.Include(x => x.Transactions).ThenInclude(t => t.FinancialAccount);
    
    var models = await cmd.ToListAsync();