NullReferenceException when adding to collection inside controller

hooman.ahmadi

New Member
\[code\][HttpPost]public ActionResult Create(Playlist playlist){ if (ModelState.IsValid) { if (Session["Playlist"] != null) { List<int> musicIds = new List<int>(); musicIds = Session["Playlist"] as List<int>; if (musicIds.Count > 0) { UserProfileRepository UserProfileRepository = new UserProfileRepository(db); string Name = this.User.Identity.Name; UserProfile User = UserProfileRepository.getModelByName(Name); playlist.UserId = User.UserId; db.Playlists.Add(playlist); db.SaveChanges(); foreach (var item in musicIds) { Music music = db.Musics.Find(item); /* * Error in the line below, it says: * Object reference not set to an instance of an object. * */ playlist.Musics.Add(music); } db.SaveChanges(); return RedirectToAction("Index"); } } } return View(playlist);}\[/code\]Hello everyone, can someone tell what is wrong in my code?I cant seem to figure out why it says " Object reference not set to an instance of an object. " when both playlist and music are instantiated.Thanks in advance!
 
Back
Top