Note that there are some explanatory texts on larger screens.

plurals
  1. POC# lambda IN clause error
    primarykey
    data
    text
    <p>I’m having issues creating an IN clause using C# and lambdas.</p> <p>I have the following method <code>GetUserList(string filtersByRoles)</code></p> <p>The variable <code>string filtersByRoles</code> can hold a comma-delimited value such as: “1,2” or “1,2,3” or “1,3,4” etc...each number represents the unique number of a Role (in other words, RoleId).</p> <p>I then have the following C# lambda query:</p> <pre><code>var query = _userRepository.GetUserList(); </code></pre> <p>Which returns an <code>IQueryable&lt;User&gt;</code> where <code>User</code> is a table from my EntityFramework.</p> <p>Once I verify if the <code>filtersByRoles</code> parameter is not null-or-empty, I need to make an <code>IN</code> clause such as:</p> <pre><code>if (!string.IsNullOrEmpty(filtersByRoles)) { //Convert *filtersByRoles* to an array of integers int[] myArray = filtersByRoles.Split(',').Select(x =&gt; int.Parse(x)).ToArray(); //Make the IN clause query = query.Where(u =&gt; myArray.Contains(u.RoleId)); } </code></pre> <p>The above code compiles...but at RUNTIME it fails with the following error message:</p> <blockquote> <p>LINQ to Entities does not recognize the method 'Boolean Contains[Int32](System.Collections.Generic.IEnumerable`1[System.Int32], Int32)' method, and this method cannot be translated into a store expression.</p> </blockquote> <hr> <p>I’ve manage to find a workaround but it involves making a call to the <code>.ToList()</code> method which I believe fetches all the data from my database and then, adds a Where() clause. But wouldn’t that defeat the purpose or create some performance issues?</p> <p>This is what I’ve done:</p> <pre><code>if (!string.IsNullOrEmpty(filtersByRoles)) { string[] myArray = filtersByRoles.Split(','); query = query.ToList().Where(u =&gt; myArray.Contains(u.RoleId.ToString())).AsQueryable(); } </code></pre> <p>I would prefer <em>not</em> to make the <code>.ToList()</code> call and avoid fetching all the data.</p> <p>Is there another way to achieve this?</p> <p>EDIT: I'm using Entity Framework 1.0 and .NET Framework 3.5</p> <p>Thanks Sincerely </p> <p>Vince</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.
 

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