强制执行 IQueryable?
我有一个“没有转换为 SQL”的方法,我想在 IQueryable 上执行该方法,有没有办法强制 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题是您希望您的方法在本地执行而不是在数据库中执行吗? 如果是这样,
AsEnumerable
就是你的朋友。 这是一个非常简单的方法,类似于:重要的是它使结果的编译时类型为
IEnumerable
而不是IQueryable
,这意味着您之后调用的任何 LINQ 查询运算符都将是 LINQ to Objects 而不是 LINQ to SQL。例如:
您可以按照其他地方的建议调用
ToList
,但如果您正在进行过滤并且实际上不需要内存中的完整列表,请调用AsEnumerable< /code> 并过滤该结果将比首先加载所有内容更有效。
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:The important thing is that it makes the compile-time type of the result
IEnumerable<T>
rather thanIQueryable<T>
, which means any LINQ query operators you call after that will be the LINQ to Objects ones instead of LINQ to SQL.For example:
You could call
ToList
as suggested elsewhere, but if you're doing filtering and don't really need the full list in memory, callingAsEnumerable
and filtering that result will be more efficient than loading everything first.然后你就可以在这个列表上做你的 linq 事情了。
and then you can do your linq stuff on that List.
当您编写了一个 LinqToSql 不知道如何转换为 SQL 的查询(这也是它所说的)时,您会收到该消息。
我不确定我是否完全明白您的要求,但据我所知,您有以下选择:
假设我们排除了#3,让我们看看其他 2 个示例。
重写它 - 为了帮助解决这个问题,我们需要您的 linq 查询。
在这里,您从初始查询中取出无法翻译的部分,然后在 Iqueryable 上调用 ToList,然后在该列表上应用查询的其余部分。
您是否可以执行查询而不存储它? 好吧,不是真的,您总是可以循环遍历结果,因此不将其存储在变量中,但显然查询的结果需要存储在某个地方。
You get that message when you have written a query that LinqToSql doesn't know how to translate into SQL (which is what it says too).
I am not sure I get exactly what you're asking, but as far as I see, you have the following options:
Assuming we rule out #3, let's look at the other 2 examples.
Rewriting it - to help with that, we need your linq query.
Here you take out the part that can't be translated from the initial query, then on your Iqueryable call ToList, and then apply the rest of the query on that list.
And can you execute the query without having to store it? Well, not really, you could always loop through the results and as such not store it in a variable, but obviously the results of the query needs to be stored somewhere.