开发者

Returning null exception on linq statement

开发者 https://www.devze.com 2023-01-15 09:40 出处:网络
There\'s probably a very simple reason for this, but when hydrating an object I\'m keep getting a \"value cannot be null\" exception:

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 ();
0

精彩评论

暂无评论...
验证码 换一张
取 消