我正在尝试将AverageRating传递给我的视图。AverageRating是查询Review Model的Icollection中项目的结果。Review Model具有Rating属性。但是我收到以下消息:
System.ArgumentNullException
每当执行get操作时,就会出现这种情况,这是可以理解的。但是,当我的代码如下所示时,我应该如何最好地处理模型或其他地方的空异常:
System.ArgumentNullException
每当执行get操作时,就会出现这种情况,这是可以理解的。但是,当我的代码如下所示时,我应该如何最好地处理模型或其他地方的空异常:
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; }
}
Reviews
不能是null
?它为什么会是NRE?文档表明它应该是ANE(因为它是扩展方法)。https://msdn.microsoft.com/en-us/library/bb338413(v=vs.110).aspx - mjwillsnull
,因为它更能反映出“我不知道”的意思,而不是“非常低的分数”。 - mjwills