Ze Carioca Silva
Ze Carioca Silva

Reputation: 443

Why my Generic List is always null?

I have class like this:

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); } }


}

And in my controller I have this:

 [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");
    }


}

The problem is in the line:

if( lugar.Reviews==null) lugar.Reviews=new List();

Everytime I execute I am getting ( lugar.Reviews==null) as true.....

Even if I already added a Review for that place, the if statement returns true.....

Upvotes: 0

Views: 642

Answers (3)

Rob G
Rob G

Reputation: 3526

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

Upvotes: 2

undefined
undefined

Reputation: 34238

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

Upvotes: 0

Display Name
Display Name

Reputation: 4732

You might want to introduce a constructor in your Lugar class and instantiate the list there. Something like this:

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

Hope this helps. of not please let me know.

P.S. another thing that is not related to your specific question, but certainly an improvement is to use view model rather than FormCollection.

It will simplify your life in a major way. For example of how to use it please take a look at this successfully answered question: What is ViewModel in MVC?

Upvotes: 0

Related Questions