Does Linq not use lazy loading when called through a generic method?

So, I have a method: I count the number in sequence with holes, this number should be the first hole or max ()

    public static int GetRegisterNumber<T>(this IQueryable<T> enumerable, Func<T, bool> whereFunc, Func<T, int?> selectFunc)
    {
        var regNums = enumerable.OrderBy(selectFunc).Where(whereFunc).ToArray();

        if (regNums.Count() == 0)
        {
            return 1;
        }

        for (int i = 0; i < regNums.Count(); i++)
        {
            if (i + 1 != regNums[i])
            {
                return regNums[i].Value + 1;
            }
        }

        return regNums.Last().Value + 1;
    }

I use it like:

var db = new SomeDataContext();
db.Goals.GetRegisterNumber(g => g.idBudget == 123, g => g.RegisterNumber);

So, I expect from linq some query like:

SELECT [t0].[id], [t0].[tstamp], [t0].[idBudget], [t0].[RegisterNumber], FROM [ref].[GoalHierarchy] AS [t0] WHERE [t0].[idBudget] = 123 ORDER BY [t0].[RegisterNumber]

instead, I get:

SELECT [t0].[id], [t0].[tstamp], [t0].[idBudget], [t0].[RegisterNumber], FROM [ref].[GoalHierarchy] AS [t0]

Thus, linq receives ALL the data in the table and then filters it, but this behavior is unacceptable because the table contains a lot of data. Is there any solution?

+1
source share
1 answer

Change your method signature to:

public static int GetRegisterNumber<T>(this IQueryable<T> enumerable, Expression<Func<T, bool>> whereFunc, Expression<Func<T, int?>> selectFunc)

Thus, it will call the appropriate extension methods for IQueryable<T>. If you only have it Func<TSource, bool>, it will call the extension method for IEnumerable<T>.

+2

All Articles