Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple where conditions in EF [duplicate]

Possible Duplicate:
Conditional Linq Queries

Using Entity Framework 4.0

I have a search condition like this

enter image description here

There are four fields that allow the users to filter their search. The conditions are all AND. The result has to omit the corresponding filter if the textbox value is String.Empty or the dropdownlist value is All. Could do this in a Stored Procedure but I am unable to mimic that at all in a Linq2SQL/ Entity Framework scenario.

My question is this, how to omit IEnumerable.Where in the Linq according to some entered values?

like image 645
naveen Avatar asked Jun 15 '11 05:06

naveen


4 Answers

You can chain your where clauses. You just need an IQueryable datasource.

var filteredData = _repository.GetAll();
//If your data source is IEnumerable, just add .AsQueryable() to make it IQueryable

if(keyWordTextBox.Text!="")
    filteredData=filteredData.Where(m=>m.Keyword.Contains(keyWordTextBox.Text));

if(LocationDropDown.SelectedValue!="All")
    filteredData=filteredData.Where(m=>m.Location==LocationDropDown.SelectedValue));

... etc....

Because it is IQueryable, the data is not fetched until you bind it so it only pulls the data you need.

like image 60
Slick86 Avatar answered Nov 06 '22 00:11

Slick86


Assuming that Location and Category are identified in your code by ids (id is the value attribute in the comboboxes items), you can do something similar to

function GetItems(string keyword, string consultant, int? locationId, int categoryId){

using(MyContextEntities context = new MyContextEntities()){
    return context.Items.Where(item => 
        (string.IsNullOrEmpty(keyword) || item.Text.Contains(keyword))
        && (string.IsNullOrEmpty(consultant) || item.Consultant.Contains(consultant))
        && (!locationId.HasValue || item.Location.Id == locationId.Value)
        && (!categoryId.HasValue || item.Category.Id == categoryId.Value)
    );
}
}
like image 40
Lucian Avatar answered Nov 05 '22 23:11

Lucian


Take a look at PredicateBuilder. It will allow you to do something like this:

IQueryable<??> SearchProducts (params string[] keywords)
{
  var predicate = PredicateBuilder.True<??>();

  foreach (string keyword in keywords)
  {
    string temp = keyword;
    if(temp != String.Empty || temp != "All")
          predicate = predicate.And(e => e.???.Contains (temp));
  }
  return dataContext.??.Where (predicate);
}

Note:

Note

like image 8
Simon Stender Boisen Avatar answered Nov 06 '22 01:11

Simon Stender Boisen


The flexible way to do this is to build up the where clause separately.

This article shows you how to do that. It takes a bit of work to initially set it up. But its worth it.

like image 2
Eranga Avatar answered Nov 06 '22 01:11

Eranga