简体   繁体   English

带有null对象的Linq-to-Sql表达式抛出NPE

[英]Linq-to-Sql expression with null object throws NPE

The following linq-to-sql expression throws null pointer exception. 以下linq-to-sql表达式抛出空指针异常。

List<string> nameList = GetNames();
db.Users.FindSync(u => nameList.Contains(u.Name))

I have found the issue is that nameList is null. 我发现问题是nameList为null。 But the following update isn't helping. 但是以下更新没有帮助。

u => nameList == null || nameList.Contains(u.Name)

I have found from google searches that NPE occurs during conversion to SQL (not during evaluation). 我从谷歌搜索中发现NPE在转换为SQL期间发生(而不是在评估期间)。 Is there a way to get around this issue? 有办法解决这个问题吗?

Think of what inside .FindSync(u => ......) happen in another context/realm/dimension and Only entity types, enumeration types or primitive types are supported in this context. 想想里面.FindSync(u => ......)在另一个上下文/领域/维度中发生的事情, Only entity types, enumeration types or primitive types are supported in this context.

You may think that "but why nameList.Contains is working" it is because library did support conversion of that to SQL. 您可能认为“但为什么nameList.Contains正在工作”这是因为库确实支持将其转换为SQL。 Sadly nameList itself is not supported, also nameList == null is not supported. 遗憾的是,不支持nameList本身,也不支持nameList == null。

Your solution should be doing null check outside/before linq maybe something like 你的解决方案应该在linq之外/之前进行空检查

var uResult = nameList == null ? db.Users.GetAll() : db.Users.FindSync(u => nameList.Contains(u.Name))

It seems you have little options here. 看来你在这里几乎没有选择。 Here is one I would normally use to tackle such problems. 这是我通常用来解决这些问题的方法。

var list = new string[] { "One", "Two", "Three" };
var list2 = new string[] { "One", "Five" };
var db = new string[] { "One", "Two", "Four" };

var conditions = new List<Func<String, bool>>();
if (list != null)
{
    conditions.Add(s => list.Contains(s));
}

if (list2 != null)
{
    conditions.Add(s => list2.Contains(s));
}

var query = db.AsEnumerable(); // AsQuerable on your side.
foreach (var condition in conditions)
{
    query = query.Where(condition);
}

var result = query.ToList(); // Outputs "One".

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM