Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq-to-Sql expression with null object throws NPE

The following linq-to-sql expression throws null pointer exception.

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

I have found the issue is that nameList is 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). Is there a way to get around this issue?

like image 621
user845279 Avatar asked Jul 04 '26 08:07

user845279


2 Answers

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.

You may think that "but why nameList.Contains is working" it is because library did support conversion of that to SQL. Sadly nameList itself is not supported, also nameList == null is not supported.

Your solution should be doing null check outside/before linq maybe something like

var uResult = nameList == null ? db.Users.GetAll() : db.Users.FindSync(u => nameList.Contains(u.Name))
like image 76
WallSky Blue Avatar answered Jul 05 '26 21:07

WallSky Blue


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".
like image 22
Ghasan غسان Avatar answered Jul 05 '26 21:07

Ghasan غسان