我创建了两个模型,见下文。使用实体框架脚手架来创建控制器和视图。
在创建评论页面中,可以选择输入int
的评论。
在我的Healthprofessional
索引视图中,我想发送给每位健康专业人员的平均评分。
我在 healthprofessional razor视图中尝试了foreach
语句,但是在razor的每个视图中只能引用一个模型,这对我来说很难。
@foreach (var item in Model.HealthReviews)
{
// get error for this foreach when I try to apply
// as item.Rating does not contain
// a public definition for getenumerator
foreach (var rating in item.Rating)
{ }
}
我正在考虑将linq应用于控制器可能是答案,但我在这个阶段花了好几个小时试图去做,而不是太熟悉linq。
关于如何推进这个问题的任何建议我将不胜感激。
public enum Profession { Counsellor, Physio, Doctor }
public class HealthProfessional
{
public int ID { get; set; }
[Required]
[StringLength(50)]
[Display(Name = "Name")]
public string Name { get; set; }
public bool AcceptsMedicalCard { get; set; }
[Required]
[StringLength(80)]
[Display(Name = "Address")]
public string Address { get; set; }
[Required]
public Profession Profession { get; set; }
public ICollection<Review> HealthReviews { get; set; }
public ICollection<Client> Clients { get; set; }
}
public class Review
{
public int ID { get; set; }
public int? ClientID { get; set; }
public int? HealthProfessionalID { get; set; }
[Required]
[Range(0, 5, ErrorMessage = "Please select number between 1 and 5")]
public int Rating { get; set; }
[Required]
public string ReviewText { get; set; }
public bool WouldRecommend { get; set; }
public virtual Client Client { get; set; }
public HealthProfessional HealthProfessional { get; set; }
}
答案 0 :(得分:0)
您已经在HealthReviews
上循环ICollection<Review>
,每个Review
都包含int Rating
。尝试循环它是没有意义的,它已经是你可以直接使用的单个值。
你的代码需要看起来像这样:
@{
int sumOfRatings = 0;
foreach (var item in Model.HealthReviews)
{
sumOfRatings += item.Rating;
// ...
}
double averageRating = Model.HealthReviews.Count > 0
? (double)sumOfRatings / Model.HealthReviews.Count
: 0;
// ...
}
答案 1 :(得分:0)
您可以在HealthProfessional
课程中添加方法来计算平均评分。
public class HealthProfessional
{
public ICollection<Review> HealthReviews { get; set; }
public double CalculateAverageRating()
{
return HealthReviews.Average(r => r.Rating);
}
}
然后,在Controller操作方法中调用该方法并将其分配给视图模型的属性。