【问题标题】:LINQ to SQL and Join two tables with OR clauseLINQ to SQL 并使用 OR 子句连接两个表
【发布时间】:2009-04-23 22:11:20
【问题描述】:

假设我有计划和文件

Dim myPlans = _context.Plans.Where(predicate1)
Dim myDocuments = _context.Documents.Where(predicate2)

我已经为每个使用 PredicateBuilder 构建了 where 子句。因此,myPlans 和 myDocuments 具有正确的 SQL 语句。

我想做的是将这两个表连接到一个 linq 语句中。我遇到的问题是,默认情况下 AND 条件是加入 where 子句。

myPlans Where 子句:(p.name like "%test%" AND p.name like "%bed%") OR (p.description like "%test%" AND p.description like "%bed%")

myDocuments Where 子句:(d.name like "%test%" AND d.name like "%bed%") OR (d.description like "%test%" AND d.description like "%bed%")

当我将两者结合起来时,desired 结果 Where 子句是:
其中 (d.ID = p.ID) AND (上面的myplans where 子句) OR (上面的mydocument where 子句)。意思是,我希望每个表中的两个 where 子句是“或”而不是“和”。

where子句的当前结果是: 其中 (d.ID = p.ID) AND (上面的 myplans where 子句) AND(上面的 mydocument where 子句)。意思是,我希望每个表中的两个 where 子句是“或”而不是“和”。

我正在形成这样的陈述:

Dim test = From d in myDocuments _
           Join p in MyPlans on d.ID Equals p.ID _
           Select d.Name, p.Name

【问题讨论】:

    标签: vb.net linq linq-to-sql where


    【解决方案1】:

    为了达到你想要的结果,你需要对单个语句进行谓词过滤和连接。

    Dim myCriteria() = {"test", "bed"}
    Dim test = from d in _context.Documents _
               join p in _context.Plans on d.ID Equals p.ID _
               where (myCriteria.Contains(d.Name) OR _
                       myCriteria.Contains(d.Descrition)) _
               OR (myCriteria.Contains(p.Name) OR _
                     myCriteria.Contains(p.Description)) _
               select Document = d.Name, Plan = p.Name
    

    【讨论】:

      【解决方案2】:

      发生这种情况是因为您正在执行“第一遍”过滤与您的谓词匹配的计划和文档,然后然后仅加入这些结果,有效地执行AND。就像 Basilio 说的,你应该在同一个过程中做你的加入/过滤。你可以试试这样的:

      Dim test = From d in _context.Documents _
                 Join p in _context.Plans on d.ID Equals p.ID _
                 Where predicate1(p) Or predicate2(d)
                 Select d.Name, p.Name
      

      或类似:

      Dim test = From d in _context.Documents _
                 From p in _context.Plans _
                 Where d.ID = p.ID And (predicate1(p) Or predicate2(d))
                 Select d.Name, p.Name
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-07-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多