我正在尝试分解 linq to 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);
}
然后我可以将原始查询更改为:
from o in _context.Orders
where LastSeasonOrders(o).Count() > 100
select o;
然而,这不起作用,但有一个例外,即运行查询时方法调用无法转换为 SQL。
关于实现这一目标的正确方法有什么快速提示吗?
怎么样-
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
);
?
最好验证生成的 SQL 是否与原始查询生成的 SQL 相同。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)