Blake Blackwell
Blake Blackwell

Reputation: 7795

Add Or Condition to Entity in Entity Framework

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

Upvotes: 8

Views: 31587

Answers (3)

itchi
itchi

Reputation: 1713

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));
  }

Upvotes: 18

Marek Karbarz
Marek Karbarz

Reputation: 29304

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));

Upvotes: 3

Reed Copsey
Reed Copsey

Reputation: 564403

You need to do:

var results = entityCollection.Where(entity => entity.Property1 == 1 || entity.Property1 == 2 || entity.Property1 == 3);

Upvotes: 23

Related Questions