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; }
}
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With