C# SQLite使用EF框架

1.创建项目后先nuget添加关于SQLite的引用:

1、SQLite.CodeFirst

2、System.Data.SQLite

2.编写实体类
 public class Student
    {
        public int ID { get; set; }

        public string Name { get; set; }

        public int Age { get; set; }

        public string Gender { get; set; }
    }

1、2步很简单不多说

3.编写上下文类:
public class StudentContext : DbContext
    {
       
        public virtual DbSet<Student> Students { get; set; }
        public StudentContext() : base("dbstudent")
        {

        }
        private StudentContext(DbConnection con) : base(con, true) { }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Student>().ToTable("Students").HasKey(p => p.ID);

            Database.SetInitializer(new SqliteCreateDatabaseIfNotExists<StudentContext>(modelBuilder));
//搜了一下说是为了在模型更改时自动删除和重新创建 SQLite 数据库
            var init = new SqliteDropCreateDatabaseWhenModelChanges<StudentContext>(modelBuilder);
        }
        static string dbPath = $"Data Source=E\\student.db";
        public static StudentContext Instance
        {
            get
            {
                System.Data.Common.DbConnection sqliteCon = SQLiteProviderFactory.Instance.CreateConnection();
                sqliteCon.ConnectionString = dbPath;
                return new StudentContext(sqliteCon);
            }
        }

        
       
    }

4.修改配置文件:

这段是用于配置 Entity Framework(EF) 框架与 SQLite 数据库的集成。

<providers>
      <provider invariantName="System.Data.SQLite" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
    </providers>

这一步可以参考一下:以SQLite作为数据库的CodeFirst模式开发及踩的坑_sqlsugar sqllite codefirts-CSDN博客

注意

1.我的配置文件里面没有定义连接字符串,因为我在代码里已经写过,

我初次尝试在配置文件里添加连接字符串:

<connectionStrings>
	  <add name="XXX" connectionString="data source=.\student.db" providerName="System.Data.SQLite" />
  </connectionStrings>

运行程序时报错:

 ①:EntityException: The underlying provider failed on Open

 ②:SqlException: Cannot open database "dbstudent" requested by the login. The login failed.
Login failed for user 'Administrator'.

搞不懂了,猜测权限问题,开始寻找其他方法

在:【C#】使用EF访问Sqlite数据库_c# sqlite ef-CSDN博客中学习后改写,其中负责连接的创建代码主要是:

(代码上方已给出)

成功创建数据库:

2.另外上面的<provider>字符串可以有多条,系统会选取第一条可用的,但是要与自己使用的数据库对应,我就是一开始发现代码可以运行,数据也可以存储,但是没有对应的数据库生成,弄了好久才发现我使用的是SQL server的程序,即为下面这种配置:

<providers>
    <provider invariantName="Microsoft.EntityFrameworkCore.SqlServer" type="Microsoft.EntityFrameworkCore.SqlServer.SqlServerProviderServices, Microsoft.EntityFrameworkCore.SqlServer" />
  </providers>
5.可以运行试一下了,demo架构很简单:

窗体根据个人喜好编写,这个一点都不专业...

以后有更深的理解再来水了,有感悟、疑问或者指正可以发在评论区一起讨论

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值