Click here to Skip to main content
15,888,610 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
In the DataSets days, I had a form with a datagrid view, and the user could enter a text in a single textbox as a filter. The program would then filter the data in the datagridView like so:

ContactBindingsource.Filter = String.Format("name like {'%0%'} or occupation Like {'%0%'}", Me.filterTextbox.Text)


I think the Filter method on a bindingsource doesn't work in EF.
What is the best practice in EF4 to do a similar thing? Do I need Entity SQL instead of LINQ to entities?

Thank you,
A.J. Nijenhuis
Posted

I`ll construct the query dinamycally depending on the parameters given.
Example, a datagrid and filters like name and country:
C#
var objSet = objContext.EntityName //returns IQueryable and over this object we add the filters
if(!string.IsNullorEmpty(txtName.Text))
{
   objSet = objSet.Where(x => x.Name.Contains(txtName.Text));
}
if(ddlCountry.SelectedValue != -1)
{
   objSet = objSet.Where(x => x.Country == ddlCountry.SelectedValue );
}
return objSet.ToList();


As the query has not been executed until we call ToList(), you can programmatically add where conditions to it and at the end it will construct the query only with the passed parameters. Look that I´m using string.Contains in place of the "like "%{0}%"" as we used to. I haven't seen how this is translated at the database but it has worked for me!
 
Share this answer
 
Interesting approach, however this seems to be throwing an invalid cast exception, which says that an ObjectQuery cannot be cast to an ObjectSet:

System.InvalidCastException occurred
Message=Unable to cast object of type 'System.Data.Objects.ObjectQuery`1[PrismaModel.Aanvraag]' to type 'System.Data.Objects.ObjectSet`1[PrismaModel.Aanvraag]'.
Source=PrismaModel
StackTrace:
at PrismaModel.AanvraagManager.GetAanvragen(String zoektekst)
InnerException:

In the mean time, I have successfully tried a dynamic query like so:

VB
Dim ctx As PrismaEntities = ConnectionManager.CreateContext

Dim filter As String = "1=1"

filter &= String.Format(" AND it.klant.realtie.naam LIKE '%{0}%')", zoektekst)

If IsNumeric(zoektekst) Then
  filter &= String.Format(" AND it.aanvraagnr = '{0}')", zoektekst)
End If

Dim q = ctx.aanvragen.Where(filter).OrderBy("it.aanvraagDatum DESC, it.Artikelnr")

Return New SortableBindingList(Of Aanvraag)(q.ToList)


Cons: the filter is not strongly typed :(
Pro's: descending ordering supported in one combined order statement.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900