Note that there are some explanatory texts on larger screens.

plurals
  1. POFilter Results with LINQ
    text
    copied!<p>I am converting an ADO.NET application to use Entity Framework 5 and have come across an issue while re-writing the search function. I have separated the UI and DB layer, the DB layer now has an internal edmx and exposes data retrieval methods.</p> <p>One such method is search. Because the function no longer has access to form control values directly(There used to be a LINQ Query on UI code-behind file) I have created a class to allow the form to pass those values across</p> <pre><code>public class SearchParameter { public string Name { get; set; } public bool Checked { get; set; } public object Value { get; set; } } </code></pre> <p><em>I know this results in boxing the value, but I could not see any another way to allow for multiple value types</em></p> <p>The search function looks like this</p> <pre><code>public static IList SearchRecords(IList&lt;SearchParameter&gt; searchParams) { using (var db = new EarnieEntities()) { var result = db.Non_Conformance; //Filter Results based on params foreach (var p in searchParams.Where(p =&gt; p.Checked)) { switch (p.Name) { case "NCID": break; case "DateRaised": break; case "RaisedBy": break; case "RaisedFor": break; } } return result.ToList(); } } </code></pre> <p>With LINQ to SQL with each of these cases I could have written something like this to filter the result set by that field</p> <pre><code>result = result.Where(x =&gt; x.NC_ID == (int) p.Value).Select(x =&gt; x); </code></pre> <p>The idea when using LINQ to SQL was to harness lazy loading and allow all of the filtering before the results were accessed. This allows users to select fields on the UI and build their search criteria. </p> <p>With EF, I get the </p> <blockquote> <p>You cannot convert source type Linq.IQueryable&lt; Type > to target type Data.Entity.DbSet&lt; Type ></p> </blockquote> <p>Is there another way to do such filtering?</p> <p>[Update]</p> <p>If I try to simply cast the result to a DbSet I get another error </p> <blockquote> <p>Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery<code>1[EarnieDAL.Sources.Non_Conformance]' to type 'System.Data.Entity.DbSet</code>1[EarnieDAL.Sources.Non_Conformance]</p> </blockquote>
 

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