0
votes

I've just learnt how to upload pictures and bring them in view Model.

Now I'm trying to Add comments to the pictures. That means a picture can have more comments. So I created 2 Tables, called "Gallery" and "Comment". They are related by 'One to Many'.. My model looks like that..


public class GalleryEntries
    {
        public List Entries { get; set; }
    }

    public class GalleryEntry
    {
        public Gallery GalleryImage { get; set; }
        public List Comments { get; set; }
    }

And the controller looks so..


GalleryDataContext GalleryDB = new GalleryDataContext();

        public ActionResult Index()
        {
            GalleryEntries model = new GalleryEntries();
            GalleryEntries galleryentries = new GalleryEntries();

            foreach (Gallery gallery in GalleryDB.Galleries)
            {
                GalleryEntry galleryentry = new GalleryEntry();
                galleryentry.Comments = GalleryDB.Comments.Where(c => c.BildID == gallery.ImageID).ToList();
                galleryentry.GalleryImage = gallery;
                galleryentries.Entries.Add(galleryentry);
            }

            return View(model);
        }

But it doesn't work. :( It displays "Object reference not set to an instance of an object" at the line where

 "galleryentries.Entries.Add(galleryentry) 
stands.. How can I solve this problem?
1

1 Answers

1
votes

I think the problem is that you don't initialize the GalleryEntries.Entries property anywhere ... so you're attempting to add galleryentry to a List that does not exist yet, hence the NullReferenceException.

You could initialize Entries in the constructor:

public class GalleryEntries
{
    public IList<GalleryEntry> Entries { get; set; }

    public GalleryEntries() {
        Entries = new List<GalleryEntry>();
    }
}