Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ, handle Null in Model

Tags:

c#

asp.net

linq

Im trying to pass AverageRating to my view. AverageRating is the result of querying items in an Icollection of Review Model. Review Model has a property of Rating. However i get this message:

System.ArgumentNullException

This happens whenever the get is performed, which is understandable. However how do i best handle null exceptions in my model or elsewhere when my code looks like the following:

public class MyModel
{

        //Querying this navigation property
        public ICollection<Review> Reviews { get; set; }

        public double? AverageRating
        {
        get
        { 
            //check that this is not null / handle null
            return Math.Round(Reviews.Average(c => c.Rating), 1);
        }

        }

}
public class Review
{
    [Key]
    public int ReviewID { get; set; }
    public int Rating { get; set; }
    public string Comment { get; set; }
    public int CoachID { get; set; }
    public int? StudentID { get; set; }


    public Coach Coach { get; set; }
    public Student Student { get; set; }
}
like image 555
thelastchief Avatar asked Jan 29 '23 01:01

thelastchief


1 Answers

This implementation may do what you need:

public double? AverageRating
{
    get
    {
        return Reviews?.Average(x => x?.Rating);
    }
}

It will deal with Reviews being null (it will return null), due to use of ? after Reviews.

It will deal with individual Reviews being null (they will be ignored in terms of calculating the Average), due to use of ? after x.

like image 124
mjwills Avatar answered Jan 31 '23 16:01

mjwills