views:

210

answers:

3

Can you add an "Or" condition to an entity in the entity framework? For example something like:

Property1 == (1 or 2 or 3)

The message I get when putting the value of "1 || 2 || 3" or "1,2,3" or "1 or 2 or 3" returns this message:

condition is not compatible with the type of the member
A: 

You need to do:

var results = entityCollection.Where(entity => entity.Property1 == 1 || entity.Property1 == 2 || entity.Property1 == 3);
Reed Copsey
I was afraid of that. What I'd like to do is for the same condition to take place every time a query against that table is executed so that I don't have to write the above code each time I hit the table.
Blake Blackwell
@Blakewell: Put the query in a utility class so you can reuse it.
Mark Byers
@Reed Copsey: Are you missing an `entity =>`?
Mark Byers
@Mark: Not anymore ;) That happens when I goof and reword things too fast.. Thanks.
Reed Copsey
+2  A: 

Haven't tried this, but you could try using contains. Not sure about performance, but the code is smaller:

int[] vals = new int[] { 1, 2, 3, 4 };
var results = entityCollection.Where(entity => vals.Contains(entity.Property1));
Marek Karbarz
`Contains` is only supported in EF 4, which hasn't been released yet (it's coming out the 12th with .Net 4). There's is a release candidate on MS's website.
BlueRaja - Danny Pflughoeft
Didn't even think about that - I've been using EF 4 for a while so this seemed normal.
Marek Karbarz
+1  A: 

You should also check out predicate builder: http://www.albahari.com/nutshell/predicatebuilder.aspx

It's a bit more advanced, but if you have to dynamically chain conditions it's your best bet.

foreach (string keyword in keywords)
  {
    string temp = keyword;
    predicate = predicate.Or (p => p.Description.Contains (temp));
  }
itchi