简体   繁体   English

Linq2Sql:在选择中使用IQueryable

[英]Linq2Sql: Using IQueryable in select

This is probably quite trivial but.... I have a quite complicated linq query that I have put in a IQueryable function that I'd like to reuse throughout the project. 这可能是微不足道的,但是...。我有一个相当复杂的linq查询,我已将其放在IQueryable函数中,希望在整个项目中重复使用。 But when I use this in a select I get "System.Linq.IQueryable`1[LINQPad.User.Orders] Foo(System.Guid) doesn't have a translation to SQL": (very simplified to show what I've after) 但是,当我在选择中使用它时,我得到“ System.Linq.IQueryable`1 [LINQPad.User.Orders] Foo(System.Guid)没有对SQL的转换” :(非常简化,以显示我所拥有的后)

void Main()
{
 (from e in Clients
 select new {
  e.CompanyName,
  Orders = Foo(e.Id).Count()
 }).Take(20).Dump();
}

IQueryable<Orders> Foo(Guid clientId)
{
 return Orders.Where(e => e.ClientId.Equals(clientId)); 
}

Doesn't work, but the following does: 无效,但以下功能可以:

void Main()
{
 (from e in Clients
 select new {
  e.CompanyName,
  Orders = Orders.Where(f => f.ClientId.Equals(e.Id)).Count()
 }).Take(20).Dump();
}

Is there any way I can rewrite the query without rewriting Foo? 有什么方法可以重写查询而不重写Foo?

The problem is that you can't just inject a function into your Linq query, because Linq-to-SQL or Linq-to-Entities doesn't know how to translate it. 问题是您不能仅仅将一个函数注入到Linq查询中,因为Linq-to-SQL或Linq-to-Entities不知道如何翻译它。 There's a good description of the problem, and a solution available at the LINQPad site. LINQPad站点提供了对该问题的详尽描述和解决方案

An alternative is to bring the dataset into memory first (eg by using ToList() ), but that won't really achieve exactly what you're after. 一种替代方法是先将数据集带入内存(例如,通过使用ToList() ),但这并不能真正实现您所追求的目标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM