Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to do a subquery in LINQ?
    primarykey
    data
    text
    <p>Here's an example of the query I'm trying to convert to LINQ:</p> <pre><code>SELECT * FROM Users WHERE Users.lastname LIKE '%fra%' AND Users.Id IN ( SELECT UserId FROM CompanyRolesToUsers WHERE CompanyRoleId in (2,3,4) ) </code></pre> <p>There is a FK relationship between <code>CompanyRolesToUsers</code> and <code>Users</code>, but it's a many to many relationship and <code>CompanyRolesToUsers</code> is the junction table.</p> <p>We already have most of our site built, and we already have most of the filtering working by building Expressions using a PredicateExtensions class.</p> <p>The code for the straightforward filters looks something like this:</p> <pre><code> if (!string.IsNullOrEmpty(TextBoxLastName.Text)) { predicateAnd = predicateAnd.And(c =&gt; c.LastName.Contains( TextBoxLastName.Text.Trim())); } e.Result = context.Users.Where(predicateAnd); </code></pre> <p>I'm trying to add a predicate for a subselect in another table. (<code>CompanyRolesToUsers</code>)</p> <p>What I'd like to be able to add is something that does this:</p> <pre><code>int[] selectedRoles = GetSelectedRoles(); if( selectedRoles.Length &gt; 0 ) { //somehow only select the userid from here ???: var subquery = from u in CompanyRolesToUsers where u.RoleID in selectedRoles select u.UserId; //somehow transform this into an Expression ???: var subExpression = Expression.Invoke(subquery); //and add it on to the existing expressions ???: predicateAnd = predicateAnd.And(subExpression); } </code></pre> <p>Is there any way to do this? It's frustrating because I can write the stored procedure easily, but I'm new to this LINQ thing and I have a deadline. I haven't been able to find an example that matches up, but I'm sure it's there somewhere.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload