【发布时间】: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