从SQLite数据库读取表始终返回null

时间:2020-05-14 05:30:15

标签: c# sqlite

我正在开发一个将在Visual Studio中使用SQLite数据库的应用程序,但是在程序初始化时,我无法使用DbContext来读写数据库。

我从这里尝试了几件事 https://ef.readthedocs.io/en/staging/platforms/netcore/new-db-sqlite.html

在这里 https://docs.microsoft.com/en-us/ef/core/get-started/?tabs=netcore-cli&fbclid=IwAR0O_1VYLJdOCm2PBf6_W42fNqTE5DpwXXghUNyvf7_92ozKQjCJcS1S6J0

这是我的代码

using Microsoft.EntityFrameworkCore;

namespace HomeHelper.Core
{
    public class HomeHelperContext : DbContext
    {
        public string Config { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlite("Data Source= Db/HomeHelper.db");
        }
    }
}

这是数据库

enter image description here

当我尝试使用以下代码阅读

        using (var db = new HomeHelperContext())
        {
            if(db!=null)
            {
                if (db.Config == null)
                {
                    db.Config = "test";
                }

                foreach (var Config in db.Config)
                {
                    if (Config != null)
                        Console.WriteLine(" - {0}", Config);
                }
                db.SaveChanges();
            }

        }

我收到此错误-

System.NullReferenceException:'对象引用未设置为对象的实例。'
为空。

请问有人可以告诉我我的错误吗?

更新: 当我手动设置Config的值时,我可以确认已将其保存在数据库中,我的问题是为什么我最初无法读取它?如果我删除“ db.Config =” test“;”即使知道数据库中已设置值,我也会收到空值。

亲切的问候!

1 个答案:

答案 0 :(得分:1)

由于您与我们共享的图片,表名是Settings,而Config只是列名。

对于映射到数据库表和视图的实体,DbContext类必须包含DbSet类型的属性。

    public DbSet<Settings> Settings { get; set; }

并声明您的Settings实体模型

    public class Settings
    {
        [Key]
        public int Id { get; set; }
        public string Config{ get; set; }

    }

之后,您可以使用db.Settings

检索“设置”中的所有数据。

,如果您想检索第一个db.Settings.FirstOrDefault();

https://docs.microsoft.com/en-us/ef/core/get-started/?tabs=netcore-cli