【问题标题】:My .saveChanges() method is not saving because it is saying an object reference is required for the non-static field, method, or property我的 .saveChanges() 方法没有保存,因为它表示非静态字段、方法或属性需要对象引用
【发布时间】:2025-12-11 03:05:02
【问题描述】:

调用 .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>());
    }
}

最后,这是我的 Song 类的代码。

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

【问题讨论】:

    标签: c# asp.net-mvc entity-framework non-static


    【解决方案1】:

    您正在尝试在此处的代码中以静态值的形式访问 public DbSet&lt;Song&gt; 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");
    }
    

    【讨论】:

      最近更新 更多