Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
创建LINQ到SQL的可重用块_Linq_Linq To Sql - Fatal编程技术网

创建LINQ到SQL的可重用块

创建LINQ到SQL的可重用块,linq,linq-to-sql,Linq,Linq To Sql,我试图将linq分解为sql查询,使它们更具可读性 假设我想退回前一年有100多个订单的产品的所有订单。我有一个疑问: from o in _context.Orders where (from o1 in _context.Orders where o1.Year == o.Year - 1 && o1.Product == o.Product select o1).Count() > 100 select o; 我希望能够将嵌套查询放在可

我试图将linq分解为sql查询,使它们更具可读性

假设我想退回前一年有100多个订单的产品的所有订单。我有一个疑问:

from o in _context.Orders
where (from o1 in _context.Orders 
       where o1.Year == o.Year - 1 && o1.Product == o.Product
       select o1).Count() > 100
select o;
我希望能够将嵌套查询放在可重用函数中:

private IQueryable<Order> LastSeasonOrders(Order order)
{
    return (from o in _context.Orders 
            where o.Year == order.Year - 1 && o.Product == order.Product
            select o);
}
但是,这不起作用,因为有一个异常,即在运行查询时无法将方法调用转换为SQL


关于实现这一目标的正确方法,有什么快速提示吗?

我只是随便说说,但是您是否尝试过将
LastSeasonOrders
的返回类型更改为
IQueryable

类似的东西呢-

void Main()
{
    TypedDataContext _context = ...

    var query = 
        (
            from o in _context.Orders  
            where LastSeasonOrders(_context , o).Count() > 100 
            select o    
        );
     ...
 }      


public static Func<TypedDataContext, Order, IQueryable<Order>> 
     LastSeasonOrders = CompiledQuery.Compile
     (( TypedDataContext _context, Order order) =>

        from o in _context.Orders
        where o.Year == order.Year - 1 && o.Product == order.Product
        select o            
);          
void Main()
{
TypedDataContext\u上下文=。。。
变量查询=
(
从上下文中的o开始
其中LastSeasonOrders(_context,o).Count()>100
选择o
);
...
}      
公共静态函数
LastSeasonOrders=CompiledQuery.Compile
((TypedDataContext\u上下文,顺序)=>
从上下文中的o开始
其中o.Year==order.Year-1&&o.Product==order.Product
选择o
);          
?


最好验证生成的sql是否与原始查询生成的sql相同。

我自己也一直在想这一点,但无法亲自询问。问题是查询提供程序无法处理查询中的任何函数调用。正如您所说,函数应该返回
IQueryable
,但这并不是真正的问题。我已经更新了这个问题,希望没有更多的困惑。
void Main()
{
    TypedDataContext _context = ...

    var query = 
        (
            from o in _context.Orders  
            where LastSeasonOrders(_context , o).Count() > 100 
            select o    
        );
     ...
 }      


public static Func<TypedDataContext, Order, IQueryable<Order>> 
     LastSeasonOrders = CompiledQuery.Compile
     (( TypedDataContext _context, Order order) =>

        from o in _context.Orders
        where o.Year == order.Year - 1 && o.Product == order.Product
        select o            
);