title: How to add a where clause on a linq join (lambda)?
body: <p>I have two database tables Contact (Id, Name, ...) and ContactOperationalPlaces (ContactId, MunicipalityId), where a contact can be connected to several ContactOperationalPlaces.</p>
  
  <p>What I'm trying to do is to build a query (ASP .NET, C#) with IQueryable, that only selects all the contacts that exists in the ContactOperationalPlaces table, with a given MunicipalityId.</p>
  
  <p>The sql query looks like this:</p>
  
  <pre><code>select * from Contacts c 
  right join ContactOperationPlaces cop on c.Id = cop.ContactId 
  where cop.MunicipalityId = 301;
  </code></pre>
  
  <p>With linq it would look something like this:</p>
  
  <pre><code>//_ctx is the context
  var tmp = (from c in _ctx.Contacts
               join cop in _ctx.ContactOperationPlaces on c.Id equals cop.ContactId
               where cop.MunicipalityId == 301
               select c);
  </code></pre>
  
  <p>So, I know how to do this if the point was to select all of this at once, unfortunately it's not. I'm building a query based on user input, so I don't know all of the selection at once.</p>
  
  <p>So this is what my code looks like:</p>
  
  <pre><code>IQueryable&lt;Contacts&gt; query = (from c in _ctx.Contacts select c);
  //Some other logic....
  /*Gets a partial name (string nameStr), and filters the contacts 
   so that only those with a match on names are selected*/
  query = query.Where(c =&gt; c.Name.Contains(nameStr);
  //Some more logic
  //Gets the municipalityId and wants to filter on it! :( how to?
  query = query.where(c =&gt; c.ContactOperationalPlaces ...........?);
  </code></pre>
  
  <p>The difference with the two where statements is that with the first one, each contact has only one name, but with the latter a contact can contain several operational places...</p>
  
  <p>I have managed to find one solution, but this solution gives me an unidentyfied object, that contains both of the tables. And I don't know how to proceed with it.</p>
  
  <pre><code>query.Join(_ctx.ContactOperationPlaces, c =&gt; c.Id, cop =&gt; cop.ContactId,
        (c, cop) =&gt; new {c, cop}).Where(o =&gt; o.cop.municipalityId == 301);
  </code></pre>
  
  <p>The object returned from this expression is System.Linq.Iqueryable&lt;{c:Contact, cop:ContactOperationalPlace}>, and it can't be cast to Contacts...</p>
  
  <p>So, that's the issue. The answer is probably pretty simple, but I just can't find it...</p>