Adam Chubbuck
Adam Chubbuck

Reputation: 1670

IQueryable with Linq expression resulting in NullReferenceException

The following function results in a NullReferenceException because it is referencing m.tags, which has not been declared in the JSON object. This is intentional. I need to query for all JSON objects that have no existing tags object.

SelectNext

TweetModel tweet = client
    .CreateDocumentQuery<TweetModel>( UriFactory.CreateDocumentCollectionUri( databaseName, collectionName), queryOptions )
    .Where( m => m.tags == null )
    .ToList()
    .FirstOrDefault();

Example Document

{
  "timestamp": "2017-07-05T19:31:18.918Z",
  "topic": "Trump",
  "score": "1",
  "sentiment": "positive",
  "text": "@gjacquette @travi44 @WSJ Where did I say trump shouldn't hire a lawyer? I said the fact his lawyers are hiring law… ",
  "id": "882683325495816192",
  "retweet_count": 0,
  "time_zone": null,
  "lang": "en",
  "screen_name": "bernielove1969"
}

Declaring empty values for the tags object solves the exception, so I am certain that this is the problem, I'm just not sure how to fix it.

I have tried modifying m => m.tags == null to !(m => m.tags != null) with no luck as well as a variety of other solutions throughout the last couple of hours. Suggestions are welcomed.

Upvotes: 2

Views: 2738

Answers (2)

Ousmane D.
Ousmane D.

Reputation: 56423

Change this:

.Where(m => m.tags == null)

to this:

.Where(m => m?.tags == null)

With the use of the Null-conditional Operator, you will not hit a NullReferenceException if m doesn't refer to an object.


Update

When dealing with IQueryable<T> queries, the lambda expressions are converted into expression trees and expression trees don't support the null conditional operator. therefore you can do .Where(m => m != null && m.tags == null) instead.

Upvotes: 6

Kevin
Kevin

Reputation: 2243

This is a bit of a shot in the dark, but I figured I'd throw it out in case it helps. It sounds like it's not an issue of m.tag being null, but that m is a dynamically created object that may not have a tag property at all. It's not that it's null/not-null, it's that it may not even be there in the object as a property or as a field.

Have you tried looking at something like:

m.GetType().GetField("tag") == null  // or...
m.GetType().GetProperty("tag") == null

... just something to try.

Upvotes: 0

Related Questions