我需要构建一个LINQ查询,允许我改变连接表上的where子句,但找不到一种方法。
我正在构建的两个查询的简化示例是:
var myQuery = from tab1 in context.Table1
join tab2 in context.Table2 on Table1.ID equals Table2.Table1ID
where tab1.TypeCode == 3
tab2.SomeID == 4 &&
select tab1.ID;
var myQuery2 = from tab1 in context.Table1
join tab2 in context.Table2 on Table1.ID equals Table2.Table1ID
where tab1.TypeCode == 3
tab2.SomeOtherID == 4 &&
select tab1.ID;
它们之间的唯一区别是tab2.SomeID where子句更改为tab2.SomeOtherID。
如果将更改的where子句应用于tab1,我可以在查询中添加.Where但是如何使用公共查询并指定不同的tab2 where子句?
答案 0 :(得分:2)
Dynamically Composing Expression Predicates
或
alt text http://www.scottgu.com/blogposts/dynquery/step2.png
你需要这样的东西吗?使用the Linq Dynamic Query Library(下载包含示例)。
查看ScottGu's blog了解更多示例。
答案 1 :(得分:1)
您可以在查询中包含可选参数:
int? someID = null;
int? someOtherID = 4;
var myQuery = from tab1 in context.Table1
join tab2 in context.Table2 on Table1.ID equals Table2.Table1ID
where tab1.TypeCode == 3
&& (someID == null || tab2.SomeID == someID)
&& (someOtherID == null || tab2.SomeOtherID == someOtherID)
select tab1.ID;
Linq-to-SQL将从查询中删除可在客户端评估的部分,因此在上面的示例中,where子句将在tab1.TypeCode和tab2.SomeOtherID上进行过滤。