我的 .saveChanges() 方法没有保存,因为它说非静态字段、方法或属性需要对象引用



调用 .保存更改((。它告诉我非静态字段,方法或属性"SongDatabase.Songs"需要对象引用。这是我的控制器代码。有人可以告诉我为什么会发生此错误吗?

[HttpPost]
    public ActionResult Add(Song song)
    {
        using (SongDatabase db = new SongDatabase())
        {
            SongDatabase.Songs.Add(song);
            SongDatabase.SaveChanges();
        }
        return RedirectToAction("Music");
    }

这是我的歌曲数据库的代码。

public class SongDatabase : DbContext
{
    public DbSet<Song> Songs { get; set; }
    public DbSet<Artist> Artists { get; set; }
    public DbSet<Album> Albums { get; set; }
    public SongDatabase()
    {
        Database.SetInitializer(new DropCreateDatabaseIfModelChanges<SongDatabase>());
    }
}

最后,这是我的歌曲类的代码。

public class Song
{
    public Song()
    {
        Album = new List<Album>();
    }
    /// <summary>
    ///  The Id of the song.
    /// </summary>
    public int SongId { get; set; }
    /// <summary>
    ///  The name of the song.
    /// </summary>
    public string SongName { get; set; }
    /// <summary>
    /// The artist of the song.
    /// </summary>
    public int ArtistId { get; set; }
    /// <summary>
    ///  The duration of the song.
    /// </summary>
    public double Duration { get; set; }
    /// <summary>
    ///  Whether or not this song should be excluded when calculating the total duration of the current playlist. 
    /// </summary>
    public bool Exclude { get; set; }
    /// <summary>
    /// Navigation property linking the album class to the song class.
    /// </summary>
    public virtual ICollection<Album> Album { get; set; }
    /// <summary>
    /// Navigation property linking the artist class to the song class.
    /// </summary>
    public virtual Artist Artist { get; set; }
}

您正在尝试将public DbSet<Song> Songs { get; set; }作为静态值访问,在此处的代码中

[HttpPost]
public ActionResult Add(Song song)
{
    using (SongDatabase db = new SongDatabase())
    {
        SongDatabase.Songs.Add(song);
        SongDatabase.SaveChanges();
    }
    return RedirectToAction("Music");
}

您使用SongDatabase db = new SongDatabase()创建SongDatabase实例,但未使用该实例db 。您应该将其更改为

[HttpPost]
public ActionResult Add(Song song)
{
    using (SongDatabase db = new SongDatabase())
    {
        db.Songs.Add(song);
        db.SaveChanges();
    }
    return RedirectToAction("Music");
}

最新更新