代码之家  ›  专栏  ›  技术社区  ›  sipsorcery

对联接表应用动态where子句

  •  2
  • sipsorcery  · 技术社区  · 14 年前

    我需要构建一个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。

    如果将changing where子句应用于tab1,我可以在查询中添加一个.where,但是如何使用公共查询并指定不同的tab2 where子句呢?

    2 回复  |  直到 14 年前
        1
  •  1
  •   KristoferA    14 年前

    查询中可以有可选参数:

    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;
    

    linqtosql将从查询中删除可在客户端计算的部分,因此在上面的示例中,where子句将在tab1.TypeCode和tab2.SomeOtherID上进行过滤。

        2
  •  2
  •   Glorfindel Doug L.    5 年前

    Dynamically Composing Expression Predicates

    alt text
    scottgu.com )

    你需要这样的东西吗?使用 the Linq Dynamic Query Library (下载包括示例)。

    ScottGu's blog 更多示例。