0

I Have this where statement in LINQ:

(users != null && users.Contains(x.Appointment.UserId))

users is an int[]. When i run this code i have an exception:

Unable to create a null constant value of type 'System.Int32[]'. Only entity types, enumeration types or primitive types are supported in this context.

What should i do?

7
  • Don't you need to use the ToList() before attempting the Contains? Commented Jul 30, 2014 at 10:12
  • Show your real code or example code that demonstrates the problem Commented Jul 30, 2014 at 10:14
  • Did you copy users to a local variable? Commented Jul 30, 2014 at 10:14
  • 1
    This is LINQ-to-SQL or Entity-Framework, right? It looks like it's attempting to translate this Where query to SQL, but the LINQ provider doesn't know how to handle int[] in the DB. Commented Jul 30, 2014 at 10:15
  • get the null-guard (users != null) out of your EF/LINQ-context ... Commented Jul 30, 2014 at 10:18

2 Answers 2

1

I had a similar problem. Assuming you are starting with something like this:

var filtered = appointments
    .Where(x => users != null && users.Contains(x.Appointment.UserId));

As @CarstenKönig suggests, try moving the null check outside of the Where clause:

var filtered = users != null ? 
    appointments.Where(x => users.Contains(x.Appointment.UserId)) :
    appointments;

That means the null check is handled by C#, and LINQ to Entities doesn't attempt to convert it to SQL.

Sign up to request clarification or add additional context in comments.

Comments

0

As others suggested you could move bool check outside the closure and use resulting bool in your Where statement:

var usersNotNull = users != null;
var users = users == null ? new string[0] : users;
query.Where(x => usersNotNull && users.Contains(x.Appointment.UserId));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.