X Pahadi
X Pahadi

Reputation: 7443

Linq Enumeration Error

I am getting users from posted form data, but sometimes it might be empty.

var users = Request.Form.GetValues("users[]") == null ? null : Request.Form.GetValues("users[]").ToArray();

So, users becomes null if empty. But, the following Linq query does not work.

 var submissions = db.QuickSearchViews.Where(x => (users != null && users.Contains(x.UserId)))
                                      .ToList();

Error:

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

Upvotes: 1

Views: 4825

Answers (2)

JNYRanger
JNYRanger

Reputation: 7097

I am going to assume that this is Entity Framework based on the error message. The reason why this query throws an error message (you didn't post the full error & stack trace, but it's most likely a NotSupportedException) is twofold

  1. users is not an entity within your context db (database mapping) and checking if it is null cannot be translated to a SQL statement.

  2. users.Contains(x.userId) cannot be translated to a SQL statement because users is not part of your database.

You'd need to reorder the way that this is written:

var users = Request.Form.GetValues("users[]") == null ? null : Request.Form.GetValues("users[]").ToArray();
if(users != null)
{
     List<QuickSearchView> qsvs = db.QuickSeachViews.ToList();
     var submississions = qsvs.Where(x => users.Any(x.UserId));
}
else
{
      //something when users is null
}

Potentially, this might work as well, but I haven't tested it and I don't remember since I haven't tried something like this recently:

var submissions = db.QuickSearchViews.Where(x => users.Any(x.UserId));

You might need to call something like db.QuickSearchViews.Load(); first though, you'll need to test it.

Pro Tip:

If you're concerned about users being null you can use the null coalescing operator ??. Since you mentioned that users is null when empty you can do this:

var users = (Request.Form.GetValues("users[]") ?? new string[0]).ToList();

This will make sure that users is never null, and therefore you don't need to check it. However, you don't even need to call ToList() on this or in your original post since Request.Form.GetValues() returns an array (string[]), which already implements IEnumerable<T> to get access to the linq extension methods.

Upvotes: 3

tede24
tede24

Reputation: 2354

users is not part of the model, so linq to entities is trying to translate it to sql and for the query it's translated as constant, then fails. Consider that the comparison users==null is being evaluated in sql not in c# so linq is trying to write the whole sentence.

I would suggest assigning an empty list instead of null when no users and eliminate users==null

Upvotes: 1

Related Questions