tika tika - 4 years ago 126
ASP.NET (C#) Question

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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download