当前位置: 首页 > news >正文

如何使用EF框架操作Sqlite

1.下载相关的NuGet

 

 

 

 2.创建如下的项目结构

3.创建AppDbContext类

using Microsoft.EntityFrameworkCore;
using SaveSyetemConfiguration.Model;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace SaveSyetemConfiguration.DBContext
{public class AppDbContext : Microsoft.EntityFrameworkCore.DbContext{// 数据库连接字符串(动态创建时可通过参数传入)private readonly string _connectionString;// 构造函数接收连接字符串(支持动态配置)public AppDbContext(string connectionString){_connectionString = connectionString;}// 实体集(对应数据库表)public Microsoft.EntityFrameworkCore.DbSet<PerSon> PersonData { get; set; } = null;// 重写 OnConfiguring 配置数据库选项protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder){if (!optionsBuilder.IsConfigured){optionsBuilder.UseSqlite(_connectionString); // 使用 SQLite 提供程序}}}
}

4.创建对应的Model类

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace SaveSyetemConfiguration.Model
{public class PerSon{[Key][DatabaseGenerated(DatabaseGeneratedOption.Identity)]public long ID { get; set; }public string Name { get; set; }public int Age { get; set; }}
}

5.在程序类进行简单的操作

using SaveSyetemConfiguration.DBContext;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace SaveSyetemConfiguration
{internal class Program{static void Main(string[] args){string DbPath = @"D:\NowText";string connectionString = "通道1";try{Directory.CreateDirectory(DbPath);connectionString = $"Data Source={DbPath}\\{connectionString}.db";AppDbContext Db = new AppDbContext(connectionString);Db.Database.EnsureCreated();Db.PersonData.Add(new Model.PerSon(){Age = 1,Name = "张三"});Db.PersonData.Add(new Model.PerSon(){Age = 1,Name = "李四"});var count = Db.SaveChanges();}catch (Exception){}}}}

结果如下:

http://www.dtcms.com/a/314622.html

相关文章:

  • K 近邻算法(KNN)完整解析:原理 + 数学公式 + 实战
  • 在Windows 11+I7+32GB内存+RTX 3060上部署Stable Diffusion 3.5 Medium详细步骤
  • Django + Vue 项目部署(1panel + openresty)
  • 制造业引入设备管理系统,实现智能资产运维与效率飞跃
  • Node.js(四)之数据库与身份认证
  • Nestjs框架: Node.js 多环境配置策略与 dotenv 与 config 库详解
  • 【计算机网络 | 第2篇】计算机网络概述(下)
  • Go 语言模糊测试 (Fuzz Testing) 深度解析与实践
  • Onnx模型部署到Arm64进行推理
  • MAC-Spring Cloud + Spring Boot + RocketMQ集成
  • 「查漏补缺」ZGC相关内容整理
  • 机器学习(13):逻辑回归
  • 一周学会Matplotlib3 Python 数据可视化-Hello World编写
  • 半同步复制原理
  • 企业级库存穿透技术实现:基于LSTM的实时损耗控制算法在快鹭AI办公系统中的实践
  • Jmeter进行性能并发测试
  • mybatis知识
  • 网安学习NO.21
  • 飞算JavaAI需求转SpringBoot项目沉浸式体验
  • 探访WAIC2025:当AI成为双刃剑,合合信息如何破解真假难题
  • 北京JAVA基础面试30天打卡01
  • SpringMvc跨域配置方法详解
  • Linux网络编程【基于UDP网络通信的群聊服务】
  • 通用代码自用
  • 李沐写作笔记
  • C语言结构体、位段、枚举、联合体
  • Codeforces Round 1004 (Div. 2)
  • win10 系统,一键保存截图, shift + print_screen
  • Ubuntu 下 MySQL 运维自动化部署教程(在线简易版)
  • 0.08B参数以小博大:用小模型生成媲美GPT-4o的古典诗词