我有这样的课:
public class Lugar
{
[Key]
public int LugarId { get; set; }
public List<Review> Reviews { get; set; }
public int SumReviews { get; set; }
public double AverageReviews { get {
if (Reviews == null)
return 0;
else if (Reviews.Count == 0)
return 0;
else
return (double)SumReviews/(Reviews.Count); } }
}
在我的控制器中,我有这个:
[HttpPost, Authorize]
public ActionResult WriteReview(int id, FormCollection formCollection)
{
Lugar lugar = db.Lugares.Find(id);
Review review=new Review();
review.User = User.Identity.Name;
review.Rating=Convert.ToInt32(formCollection["Rating"]);
review.Texto = formCollection["Review"];
if (lugar != null)
{
if( lugar.Reviews==null)
lugar.Reviews=new List<Review>();
lugar.Reviews.Add(review);
lugar.SumReviews += review.Rating;
db.SaveChanges();
}
else
return RedirectToAction("Index");
return RedirectToAction("Index");
}
}
问题在于:
if(lugar.Reviews==null) lugar.Reviews=new List();
每次我执行时,我都会得到(lugar.Reviews==null)为真.....
即使我已经为那个地方添加了评论,if 语句也会返回 true .....