如何重构多个类似的Linq-To-Sql查询? [英] How to refactor multiple similar Linq-To-Sql queries?
问题描述
Read before downvoting or closing: This almost exact duplicate of a previous question of mine exists with the solely purpose to rephrase the previous question to the Linq-To-Sql scope. All answers contained in the previous question are valid for the Linq scope, but are invalid in the Linq-To-SQL scope.
假设我要重构以下两个Linq-To-SQL查询:
Suppose I have the two following Linq-To-SQL queries I want to refactor:
var someValue1 = 0;
var someValue2= 0;
var query1 = db.TableAs.Where( a => a.TableBs.Count() > someValue1 )
.Take( 10 );
var query2 = db.TableAs.Where( a => a.TableBs.First().item1 == someValue2)
.Take( 10 );
请注意,只有Where参数会更改.有什么方法可以将查询放入方法中,并将Where参数作为参数传递?
Note that only the Where parameter changes. There is any way to put the query inside a method and pass the Where parameter as an argument?
已经尝试了上一个问题中发布的所有解决方案.尝试枚举结果时在运行时失败.
All the solutions posted in the previous question have been tried and failed in runtime when I try to enumerate the result.
抛出的异常是:查询运算符'Where'使用了不受支持的重载"
The exception thrown was: "Unsupported overload used for query operator 'Where'"
推荐答案
绝对.您会写:
public IQueryable<A> First10(Expression<Func<A,bool>> predicate)
{
return db.TableAs.Where(predicate).Take(10);
}
(假设TableA
是IQueryable<A>
.)
致电:
var someValue1 = 0;
var someValue2= 0;
var query1 = First10(a => a.TableBs.Count() > someValue1);
var query2 = First10(a => a.TableBs.First().item1 == someValue2);
我相信会起作用的...
此方法与您上一个问题的答案之间的区别基本上是,此方法使用Expression<Func<T,bool>>
而不是Func<T,bool>
,因此最终使用Queryable.Where
而不是Enumerable.Where
.
The difference between this and the answers to your previous question is basically that this method takes Expression<Func<T,bool>>
instead of just Func<T,bool>
so it ends up using Queryable.Where
instead of Enumerable.Where
.
这篇关于如何重构多个类似的Linq-To-Sql查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!