C# – Simple conditional LINQ query in Entity Framework 4

.netc++entity-frameworkentity-framework-4linq

I have recently migrated this code to Entity Framework 4 and it is failing. Obviously if status does not have a value, return all matches, if it does have a value match ones where user.StatusID == 1.

return users.SingleOrDefault(
                user =>
                user.Username == username &&
                user.EncryptedPassword == password &&
                (!status.HasValue || user.StatusID == 1)
                );

Exception returned:

ArgumentException: The specified value is not an instance of type 'Edm.Int32'
Parameter name: value

However, removing the conditional test and it works fine:

return users.SingleOrDefault(
                user =>
                user.Username == username &&
                user.EncryptedPassword == password &&
                user.StatusID == 1
                );

Any ideas? How do you perform conditional testing in EF 4? Surely not separate if lines?

I use these conditional tests time and time again in Linq to Sql; it is really odd as to why this is not functioning in EF 4. There must be something simple going wrong, perhaps there is a recommended alternate way of doing things in EF 4.0.

Thanks for your help guys,
Graham

Best Solution

Ok, I solved it by a combination of two things.

  1. Doing a simple null test.
  2. Testing the local cast status variable without the .Value method.

Both must be in place otherwise it will continue to fail with the error! It would have been nice to test the value property, but I guess the query must be really simple - quite interesting!

return users.SingleOrDefault(
                user =>
                user.Username == username &&
                user.EncryptedPassword == password &&
                (status == null || user.StatusID == (int) status)
                );

I will wait for any better implementation otherwise accept my own answer. But thanks for everybody's help.