YUN
学习工作赚钱对象是正事
学习编程技术

C#通过EF方式使用Sqllite数据库

  1. 引用Nuget包 Microsoft.EntityFrameworkCore.Sqlite
  2. 创建数据模型类
  [Index(nameof(Index))]//添加索引
  public class CacheChannelModel
  {
      [Key]//主键
      [DatabaseGenerated(DatabaseGeneratedOption.Identity)]  //设置自增
      public int Id { get; set; }
      public int Index { get; set; }
      public byte[] CacheData { get; set; }
  }
  1. 创建DbContext
    public class Cache_DBContext : DbContext
    {
        private string SavePath { get; set; }
        private string FileMD5 { get; set; }
        public Cache_DBContext(string savePath, string md5)
        {
            SavePath = savePath;
            FileMD5 = md5;
        }

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

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {

        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
            optionsBuilder.EnableThreadSafetyChecks(false);
            optionsBuilder.UseSqlite($"Data Source={SavePath}{FileMD5}.db");
        }
    }
  1. 实例化DbContext创建数据库
     Cache = new Cache_DBContext(CachePath, FileKey);
     Cache.Database.EnsureCreated();
  1. 增删改查操作

发表回复

textsms
account_circle
email

学习编程技术

C#通过EF方式使用Sqllite数据库
引用Nuget包 Microsoft.EntityFrameworkCore.Sqlite 创建数据模型类 [Index(nameof(Index))]//添加索引 public class CacheChannelModel { [Key]//主键 [DatabaseGe…
扫描二维码继续阅读
2024-11-20