我正在从发布的表单数据中获取用户,但有时它可能是空的。
var users = Request.Form.GetValues("users[]") == null ? null : Request.Form.GetValues("users[]").ToArray();
因此,如果 users 为空,则变为 null。但是,以下 Linq 查询不起作用。
var submissions = db.QuickSearchViews.Where(x => (users != null && users.Contains(x.UserId)))
.ToList();
错误:
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.
请您参考如下方法:
我将根据错误消息假设这是 Entity Framework。此查询抛出错误消息(您没有发布完整的错误和堆栈跟踪,但很可能是 NotSupportedException)的原因是双重的
users不是您上下文中的实体db(数据库映射)并检查它是否为 null 无法转换为 SQL 语句。users.Contains(x.userId)无法转换为 SQL 语句,因为用户不是您的数据库的一部分。
你需要重新排序它的书写方式:
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
}
可能,这可能也能工作,但我没有测试过,我不记得了,因为我最近没有尝试过这样的事情:
var submissions = db.QuickSearchViews.Where(x => users.Any(x.UserId));
您可能需要调用类似 db.QuickSearchViews.Load(); 的方法不过首先,您需要对其进行测试。
专业提示:
如果您担心用户为空,您可以使用 null coalescing operator ?? .既然你提到了users为空时为 null 你可以这样做:
var users = (Request.Form.GetValues("users[]") ?? new string[0]).ToList();
这将确保用户永远不会 null ,因此您不需要检查它。但是,您甚至不需要调用 ToList()自Request.Form.GetValues() 以来在此或您的原始帖子中返回一个数组 ( string[] ),它已经实现了 IEnumerable<T>访问 linq 扩展方法。
