Jaan
Jaan

Reputation: 3393

How to use multiple statements in where clause EF 5.0?

I am very new to EF 5. I have a simple search requirements where a user can search a given entitiy (Say customer) based on several search criteria. User may choose to use a criteria or not. The search conditions need to 'AND' all the criteria. So I write code like this

IQueryable _customer;
_customer = from c in context.Customer                       

    where 
                (txtCustomerName.Text.Length == 0 || c.name == txtCustomerName.Text)
                && (txtpropcust1.Text.Length == 0 || c.customfield1 == txtpropcust1.Text)
                && (txtpropcust2.Text.Length == 0 || c.customfield2 == txtpropcust2.Text)
                && (txtpropcust3.Text.Length == 0 || c.customfield3 == txtpropcust3.Text)
                && (txtpropcust4.Text.Length == 0 || c.customfield4 == txtpropcust4.Text)
                && (txtpropcust5.Text.Length == 0 || c.customfield5 == txtpropcust5.Text)

                select c;

    GridView1.DataContext = _customer;  

I am getting error saying that "Data binding directly to a store query (DbSet, DbQuery, DbSqlQuery) is not supported. Instead populate a DbSet with data, for example by calling Load on the DbSet, and then bind to local data. For WPF bind to DbSet.Local. For WinForms bind to DbSet.Local.ToBindingList()".

Is there any alternate way to proceed?

Upvotes: 1

Views: 364

Answers (2)

Andrew
Andrew

Reputation: 8674

Edit: I misunderstood the question, perhaps. But I would assume you can't bind direclty to an IQueryable, so you might need .ToList() or .ToEnumerable(). Our provider (db2) doesn't like that syntax, hence my answer. The real solution was pointed out by @Tieson T.

Not sure your exact issue, but usually you do this by using an if. You can write a simple extension method to wrap up this logic if it's needed in lots of places

var query = from d in db.Customers;

if (text1.Length > 0) query = query.Where(x => x.Field == text1)
if (text2.Length > 0) query = query.Where(x => x.Other == text2)

var data = query.ToList(); // etc

Upvotes: 2

Tieson T.
Tieson T.

Reputation: 21191

Since I'm assuming from

GridView1.DataContext = _customer;

that you're using WPF, the error is pretty much telling you all you need to know; you can't databind directly to the DbSet that EntityFramework created for you. As simple fix is likely:

GridView1.DataContext = _customer.AsEnumerable();

Upvotes: 2

Related Questions