RMD
RMD

Reputation: 3253

Using an array of enumeration values in a where clause with Entity Framework 5

I'm using EF 5. My Entity has an property called Status which is an enum of type MyEntityStatus.

I need to do a query where I return all entities that have any of a list of statuses.

My basic code is as follows:

var statusArray = new MyEntityStatus[]{MyEntityStatus.Status1, MyEntityStatus.Status2};
var results = myDataContext.MyEntities..Where(e => statusArray.Contains(e.Status)).ToArray();

Code compiles, but EF returns the following error:

The type 'MyEntityStatus' does not match the EDM enumeration type 'MyEntityStatus' or its underlying type 'Byte'.

If I try to just use an array of bytes rather than the explicit enum type, I get the following error:

DbExpressionBinding requires an input expression with a collection ResultType.

Any ideas?

Upvotes: 1

Views: 2023

Answers (1)

RMD
RMD

Reputation: 3253

Switching from Any() to Contains() got me part of the way there, but the final solution required using a List rather than a byte[].

Here is the final code that works:

var statusArray = (new MyEntityStatus[]{MyEntityStatus.Status1, MyEntityStatus.Status2}).Cast<byte>().ToList();
var results = myDataContext.MyEntities..Where(e => statusArray.Contains((byte)e.Status)).ToArray();

Apparently, EF treats a List differently from byte[].

See: .NET Entity Framework - Using .Contains() to find a byte value in a Where expression

Upvotes: 1

Related Questions