IQueryable 与 Linq 表达式导致 NullReferenceException

IQueryable with Linq expression resulting in NullReferenceException

以下函数导致 NullReferenceException,因为它正在引用 m.tags,而 m.tags 尚未在 JSON 对象中声明。这是故意的。我需要查询没有现有 tags 对象的所有 JSON 对象。

选择下一步

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

示例文档

{
  "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"
}

tags 对象声明空值解决了异常,所以我确定这就是问题所在,我只是不确定如何解决它。

在过去的几个小时里,我尝试过将 m => m.tags == null 修改为 !(m => m.tags != null),但没有成功,也尝试过各种其他解决方案。欢迎提出建议。

改变这个:

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

对此:

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

使用 Null-conditional Operator,如果 m 未引用对象,您将不会命中 NullReferenceException


更新

处理IQueryable<T>查询时,lambda表达式被转换为表达式树,表达式树不支持空条件运算符。因此您可以改为 .Where(m => m != null && m.tags == null)

这有点摸不着头脑,但我想我会把它扔掉以防万一。听起来这不是 m.tag 为 null 的问题,而是 m 是一个动态创建的对象,可能根本没有标签 属性。并不是说它是 null/not-null,而是它甚至可能不作为 属性 或字段存在于对象中。

你有没有试过看这样的东西:

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

...只是一些尝试。