带有 Linq 表达式的 IQueryable 导致 NullReferenceException

Ada*_*uck 1 c# linq lambda

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

选择下一步

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

示例文档

{
  "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"
}
Run Code Online (Sandbox Code Playgroud)

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

在过去的几个小时内,我尝试修改m => m.tags == null!(m => m.tags != null),但没有运气以及各种其他解决方案。欢迎提出建议。

Ous*_* D. 5

改变这个:

.Where(m => m.tags == null)
Run Code Online (Sandbox Code Playgroud)

对此:

.Where(m => m?.tags == null)
Run Code Online (Sandbox Code Playgroud)

使用Null-conditional Operator 时,您将不会遇到不引用对象的NullReferenceExceptionif m


更新

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