Returning null exception on linq statement
There's probably a very simple reason for this, but when hydrating an object I'm keep getting a "value cannot be null" exception:
public class MyObject
{
public MyObject() {
}
public virtual IList<MemberObject> MemberObjects { get; protected set; }
[JsonProperty] public virtual SubObject LastMemberObject {
get { return MemberObjects.OrderB开发者_StackOverflowyDescending(x => x.CreatedOn).FirstOrDefault() ?? null; }
}
}
When hydrating the object, if the MemberObjects is null, LastMemberObject throws a cannot be null exception. What's the deal?
If MemberObjects is null you will get this exception if you attempt to access a method or property such as OrderByDescending. Try this:
[JsonProperty] public virtual SubObject LastMemberObject {
get { return MemberObjects != null? MemberObjects.OrderByDescending(x => x.CreatedOn).FirstOrDefault() : null; }
}
If the object MemberObjects
is null, you can't call any instance methods on it.
[JsonProperty]
public virtual SubObject LastMemberObject {
get {
return MemberObjects != null
? MemberObjects.OrderByDescending(x => x.CreatedOn).FirstOrDefault()
: null; }
}
Also, when you're calling the FirstOrDefault()
method, this "default has to be specified as well.
MemberObjects
.OrderByDescending (x => x.CreatedOn)
.Default (something)
.FirstOrDefault ();
精彩评论