views:

1791

answers:

2

Let's say I have Plans and Documents

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

I have structured the where clause for each using PredicateBuilder. So, myPlans and myDocuments have a correct SQL statement.

What I'd like to do is join these two tables into one linq statement. The problem I'm having is that, by default the AND condition is joining the where clauses.

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

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

When I combine the two the desired result Where clause is:
Where (d.ID = p.ID) AND (myplans where clause above) OR (mydocument where clause above). Meaning, I'd like the two where clauses in each of the tables to be "or" instead of "And".

The current result where clause is: Where (d.ID = p.ID) AND (myplans where clause above) AND (mydocument where clause above). Meaning, I'd like the two where clauses in each of the tables to be "or" instead of "And".

I'm forming the statement like this:

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

In order to achieve your desired result, you need to do the predicate filterings and joins in on single statement.

Dim myCriteria() = {"test", "bed"}
Dim test = from d in _context.Documents _
           join p in _context.Plans on d.ID = 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
Jose Basilio
+1  A: 

This is happening because you are doing a "first pass" which filters the plans and documents that match your predicates, and then joining those results only, effectively doing an AND. Like Basilio said, you should do your join/filter in the same pass. You might try something like this:

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

Or similarly:

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
Lucas
I like your answer too. +1
Jose Basilio