Reputation: 4607
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.
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
public class SearchParameter
{
public string Name { get; set; }
public bool Checked { get; set; }
public object Value { get; set; }
}
I know this results in boxing the value, but I could not see any another way to allow for multiple value types
The search function looks like this
public static IList SearchRecords(IList<SearchParameter> searchParams)
{
using (var db = new EarnieEntities())
{
var result = db.Non_Conformance;
//Filter Results based on params
foreach (var p in searchParams.Where(p => p.Checked))
{
switch (p.Name)
{
case "NCID":
break;
case "DateRaised":
break;
case "RaisedBy":
break;
case "RaisedFor":
break;
}
}
return result.ToList();
}
}
With LINQ to SQL with each of these cases I could have written something like this to filter the result set by that field
result = result.Where(x => x.NC_ID == (int) p.Value).Select(x => x);
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.
With EF, I get the
You cannot convert source type Linq.IQueryable< Type > to target type Data.Entity.DbSet< Type >
Is there another way to do such filtering?
[Update]
If I try to simply cast the result to a DbSet I get another error
Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery
1[EarnieDAL.Sources.Non_Conformance]' to type 'System.Data.Entity.DbSet
1[EarnieDAL.Sources.Non_Conformance]
Upvotes: 0
Views: 2759
Reputation: 2246
The reason why you are getting that error is because you initialized "result" as a DbSet and then try to assign an IQueryable to it later.
You could initialize result using result = db.Non_Conformance.AsQueryable()
Upvotes: 3