0

我有这样的课:

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 .....

4

3 回答 3

2

Try using the 'virtual' keyword where you declare your List and see if you have any more luck.

于 2013-03-30T00:15:28.593 回答
0

您可能想在您的Lugar类中引入一个构造函数并在那里实例化列表。像这样的东西:

public void Lugar()
{
   Reviews = new List<Review>();
}

希望这可以帮助。不请告诉我。

PS另一件事与您的具体问题无关,但肯定是使用视图模型而不是FormCollection。

它将在很大程度上简化您的生活。例如如何使用它,请看一下这个成功回答的问题:什么是 MVC 中的 ViewModel?

于 2013-03-30T00:07:42.027 回答
0

You have 2 options here, lazy loading (which is enabled by putting virtual on navigation properties) This will pull down your second entitiy when you access the property in C# or eager loading by using a .Include(/*lambda or string property name*/) statement in your query.

Personally i perfer eager loading as you have more control over when entities are loaded

于 2013-03-30T00:20:54.873 回答