Linq does not lazy load if invoked via generic met

2019-06-04 20:44发布

so, i have a method: I'm counting a number in a 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'm getting:

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

So linq gets ALL the table data and then filters it, but that behavior is not acceptable, because the table contains much data. Is there any solution?

1条回答
老娘就宠你
2楼-- · 2019-06-04 21:38

Change your method signature to look like this:

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

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

查看更多
登录 后发表回答