Q:

How to toggle EntityFramework Tracker using boolean variable

I need code related help. Currently I am turning on Tracking and NoTracking using a boolean variable.  Wanted to check if there is a better way to write this code:
private Task<TEntity> GetWithOrWithoutTracking(Expression<Func<TEntity, bool>>
          predicate, bool isTracked = false)
{
    if (isTracked)
        return _dbSet.Where(predicate).AsTracking()
                    .FirstOrDefaultAsync();
    else
        return _dbSet.Where(predicate).AsNoTracking()
            .FirstOrDefaultAsync();
    }
}

A:

I don't see much wrong in your example (except the else not being super useful), but for re-usability's sake, you could use a extension method.
public static class QueryableExtensions
{
    public static IQueryable<T> AsMaybeTracking<T>(this IQueryable<T> source, bool isTracked = false) where T : class
    {
        return isTracked ? source.AsTracking() : source.AsNoTracking();
    }
}

