微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我正在尝试使用 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 举报,一经查实,本站将立刻删除。