强制执行IQueryable? [英] Force an IQueryable to execute?

查看:138
本文介绍了强制执行IQueryable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对IQueryable执行无法转换为SQL"的方法,有没有一种方法可以强制IQueryable执行而不必将其存储在某些中间类中?

I have a method that 'has no translation to SQL' that I want to perform on an IQueryable, is there a way to force the IQueryable to execute without having to store it in some intermediate class?

推荐答案

问题是您希望您的方法在本地而不是在数据库中执行吗?如果是这样,AsEnumerable是您的朋友.这是一种非常简单的方法,例如:

Is the problem that you want your method to execute locally rather than in the database? If so, AsEnumerable is your friend. It's a very simple method, something like:

public IEnumerable<T> AsEnumerable(IEnumerable<T> source)
{
    return source;
}

重要的是,它使结果的编译时类型为IEnumerable<T>而不是IQueryable<T>,这意味着您之后调用的任何LINQ查询运算符将是LINQ to Objects而不是LINQ to SQL.

The important thing is that it makes the compile-time type of the result IEnumerable<T> rather than IQueryable<T>, which means any LINQ query operators you call after that will be the LINQ to Objects ones instead of LINQ to SQL.

例如:

var query = context.Employees
                   // Filtering performed in SQL
                   .Where(emp => emp.IsFullTime)
                   .AsEnumerable()
                   // Projection performed locally; ComputeSalary has no
                   // SQL equivalent
                   .Select(emp => new { Employee = emp,
                                        Salary = ComputeSalary(emp) });

您可以按照其他地方的建议调用ToList,但是如果您正在执行过滤操作,而实际上并不需要内存中的 full 列表,则调用AsEnumerable并过滤 that 结果将比先加载所有内容更有效.

You could call ToList as suggested elsewhere, but if you're doing filtering and don't really need the full list in memory, calling AsEnumerable and filtering that result will be more efficient than loading everything first.

这篇关于强制执行IQueryable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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