尝试在数据库中建立关系时“未将对象引用设置为对象的实例”

问题描述

我正在尝试使用 sqlite 和实体框架来学习关系数据库, 我使用 Db browser for sqlite 创建了一个 database.db,其中有 2 个表:albumssongs

albums table description

songs table description

here's the DbContext to manage them.: 

namespace sqlite_test2
{
    public class DatabaseContext : DbContext
    {
        public DbSet<album> albums { get; set; }
        public DbSet<song> songs { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder dbContextOptionsBuilder)
        {
            dbContextOptionsBuilder.Usesqlite("Data Source =database.db");
        }
    }


    public class album
    {
        public int id { get; set; }
        public string title { get; set; }
        public string artist { get; set; }
        public List<song> songs { get; set; }

    }
    public class song
    {
        public int id { get; set; }
        public string songname { get; set; }

        public int albumId { get; set; }

        public album album { get; set; }
    }

}

现在我尝试为两个表创建示例条目并建立关系:

class Program
{
    static void Main(string[] args)
    {

        using ( var database = new DatabaseContext() )
        {
            //create entries. Entries are added succesfully if yo do it without relationship
            database.albums.Add(new album() { artist = "Slayer",title = "Reign in Blood" });
            database.songs.Add(new song() { songname = "Angel of Death" });

            //make a relationship
            var myAlbum = database.albums.Find(1);
            var mySong = database.songs.Find(1);
            //System.NullReferenceException: "Object 
            //reference not set to an instance of an 
            //object."
            //sqlite_test2.album.songs.get returned null.
            myAlbum.songs.Add(mySong);

            database.SaveChanges();
        }
    }
}

EDIT:按照@Andre.SanTarosa 的建议,我在制作表格条目后通过添加 database.SaveChanges(); 来编辑代码。它将条目添加数据库并给出 sqlite_test2.album.songs.get returned null. 异常:

class Program
{
    static void Main(string[] args)
    {

        using ( var database = new DatabaseContext() )
        {
            database.albums.Add(new album() { artist = "Slayer",title = "Reign in Blood" });
            database.songs.Add(new song() { songname = "Angel of Death" });
            database.SaveChanges();
            var myAlbum = database.albums.Find(1);
            var mySong = database.songs.Find(1);
            myAlbum.songs.Add(mySong);
            database.SaveChanges();
            //var mishaAlbum = database.albums.Find(4);
            //var mishaSong = database.songs.Find(1);
            //mishaAlbum.songs.Add(mishaSong);

        }
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)