如何重构多个类似的Linq-To-Sql查询?

在downvoting或closing之前阅读:这与我之前的一个问题几乎完全相同,只是为了将上一个问题重新改写为Linq-To-Sql范围。 上一个问题中包含的所有答案都对Linq范围有效,但在Linq-To-SQL范围内无效。

假设我想要重构以下两个Linq-To-SQL查询:

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参数作为参数传递?

当我尝试枚举结果时, 上一个问题中发布的所有解决方案都已在运行时尝试失败。

引发的exception是:“用于查询运算符的不支持的重载’Where’”

绝对。 你写的:

 public IQueryable First10(Expression> predicate) { return db.TableAs.Where(predicate).Take(10); } 

(假设TableAIQueryable 。)

称之为:

 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所以最终使用Queryable.Where而不是Enumerable.Where

如果您真的想要可重用性,可以尝试编写自己的运算符。 例如,而不是重复写:

 var query = Products .Where(p => p.Description.Contains(description)) .Where(p => p.Discontinued == discontinued); 

你可以编写简单的方法:

 public static IEnumerable ByName(this IEnumerable products, string description) { return products.Where(p => p.Description.Contains(description)); } public static IEnumerable AreDiscontinued(IEnumerable products, bool isDiscontinued) { return products.Where(p => p.Discontinued == discontinued); } 

然后像这样使用它:

 var query = Products.ByName("widget").AreDiscontinued(false);