C
C#2y ago
Argonak

✅ Linq 'nullable objects must have value' error source

I'm attempting to build up a query but I'm having issues with this group by. When I try to perform .ToListAsync() I get the desired results but for further code reasons .CountAsync() needs to also be functional but I keep getting this error. -The TenantId is a nullable field but in the database there is 0 records where it's actually null. -In this screenshot I'm setting the whole group g.ToList() but in reality I only need access to the Name field and TenantId, pre-encountering this it was g.Select(x => x.Name).ToList() I have tried quite a few things but can't seem get rid of the error, even knowing the source of the problem would be helpful.
13 Replies
Omnissiah
Omnissiah2y ago
why don't you use string.IsEmpty(f.Name) instead of != string.Empty can you verify just the data, like cut the query at the where and look that everything is alright
Thinker
Thinker2y ago
The DB provider probably can't translate string.IsEmpty
Omnissiah
Omnissiah2y ago
would this use linq expressions? mmm
Thinker
Thinker2y ago
Well, they have a field called _dbProvider And they're also using query syntax for some reason And anonymous objects
Omnissiah
Omnissiah2y ago
it's fiiiine
Thinker
Thinker2y ago
And if you look at the inline type hints, it says IQueryable
Argonak
ArgonakOP2y ago
If i rewrite it as method syntax it results in the same problem.
var tenantFeatureQuery = context.TenantFeatureSettings
.Where(f => f.TenantId.HasValue && f.Name != string.Empty)
.GroupBy(f => f.TenantId)
.Select(g => new { TenantId = g.Key.Value, FeatureList = g.ToList() });
var tenantFeatureQuery = context.TenantFeatureSettings
.Where(f => f.TenantId.HasValue && f.Name != string.Empty)
.GroupBy(f => f.TenantId)
.Select(g => new { TenantId = g.Key.Value, FeatureList = g.ToList() });
I can leave this filter out, each record in fact contains a string. The provider can translate it because .ToListAsync works perfectly fine with that piece in it.
Omnissiah
Omnissiah2y ago
i don't know, maybe try posting the exception
Argonak
ArgonakOP2y ago
here's the stacktrace with a few elements hidden for privacy reasons, the error message is in the title "Nullable object must have a value."
Omnissiah
Omnissiah2y ago
dunno could you try .Select(g => new { TenantId = g.Key.Value, FeatureList = g.Any() ? g.ToList() : null }); null or Array.Empty, whatever
Argonak
ArgonakOP2y ago
I have tried this and the result remains the same where I can only generate a list and no count
Omnissiah
Omnissiah2y ago
have you then tried reproducing this in a minimal project
Argonak
ArgonakOP2y ago
Began on it earlier but had to leave pc, will continue on it tomorrow Can probably mark this as solved. In my console app in memory and exact replica of data my query works fine for both ToListAsync() and .CountAsync(). There will be another thing causing my problem.
Want results from more Discord servers?
Add your server