如果通过通用方法调用,Linq不会延迟加载吗? [英] Linq does not lazy load if invoked via generic method?

查看:79
本文介绍了如果通过通用方法调用,Linq不会延迟加载吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有一个方法:我在一个带孔的序列中计算一个数字,这个数字应该是第一个孔或max()

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;
    }

我使用它的方式是:

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

因此,我希望从linq中获得一些查询,例如:

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]

相反,我得到了:

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

因此linq会获取所有表数据,然后对其进行过滤,但是这种行为是不可接受的,因为该表包含许多数据.有什么解决办法吗?

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?

推荐答案

更改您的方法签名,如下所示:

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)

这样,它将为IQueryable<T>调用适当的扩展方法.如果只有Func<TSource, bool>,它将为IEnumerable<T>调用扩展方法.

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>.

这篇关于如果通过通用方法调用,Linq不会延迟加载吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆