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

大家好,有人能告诉我的代码有什么问题吗?我似乎无法弄清楚为什么它说“对象引用未设置为对象的实例。”当播放列表和音乐都被实例化时。

提前致谢!

4

1 回答 1

1

那意味着那playlist.Musics是空的。
您应该在构造函数中对其进行初始化。

于 2012-12-04T22:27:46.663 回答