[英]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. 以下函数会导致NullReferenceException,因为它引用了
m.tags
,而该对象尚未在JSON对象中声明。 This is intentional. 这是故意的。 I need to query for all JSON objects that have no existing
tags
object. 我需要查询没有现有
tags
对象的所有JSON对象。
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. 声明
tags
对象的空值可以解决该异常,因此可以确定这是问题所在,我不确定如何解决。
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. 我已经尝试将
m => m.tags == null
修改为!(m => m.tags != null)
,在过去的两个小时中没有运气,以及其他各种解决方案。 Suggestions are welcomed. 欢迎提出建议。
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. 使用Null-conditional运算符 ,如果
m
不引用对象,则不会出现NullReferenceException
。
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. 处理
IQueryable<T>
查询时,lambda表达式将转换为表达式树,并且表达式树不支持空条件运算符。 therefore you can do .Where(m => m != null && m.tags == null)
instead. 因此您可以执行
.Where(m => m != null && m.tags == null)
。
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.
听起来这不是m.tag为null的问题,但m是动态创建的对象,可能根本没有tag属性。 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.
不是因为它为null / not-null,而是它甚至可能不存在于对象中作为属性或字段。
Have you tried looking at something like: 您是否尝试过查看以下内容:
m.GetType().GetField("tag") == null // or...
m.GetType().GetProperty("tag") == null
... just something to try. ...只是一些尝试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.