using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel.DataAnnotations; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataVAPI.ProcessServices.文件存储 { public class SqlContext : DbContext where T : DataVModel, new() { public static SqlContext Base = new(); public SqlContext() { } public static string path { get { Directory.CreateDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AccessFile")); return $"{AppDomain.CurrentDomain.BaseDirectory}AccessFile\\{typeof(T).Name}.db"; } } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlite($"FileName={path}"); } private static readonly object SqliteLock = new object(); public DbSet DbObj { get; set; } /// /// 保存数据 /// public void Save() { Database.EnsureCreated(); SaveChanges(); } /// /// 添加或者更新 /// /// public void AddToUpdat(T obj) { lock (SqliteLock) { var result = DbObj.FirstOrDefault(t => t.Id.Equals(obj.Id)); if (result != null) result.json = obj.json; else DbObj.Add(obj); Database.EnsureCreated(); SaveChanges(); } } /// /// 添加记录 /// /// /// public void Add(T obj) { lock (SqliteLock) { DbObj.Add(obj); } } /// /// 获取信息 /// /// /// public T GetInfo(string ID) { lock (SqliteLock) { Database.EnsureCreated(); return DbObj.FirstOrDefault(t => t.Id.Equals(ID)); } } /// /// 获取数据集合 /// /// public List GetLists() { lock (SqliteLock) { Database.EnsureCreated(); return DbObj.ToList(); } } /// /// 删除信息 /// /// /// public void Remove(string ID) { lock (SqliteLock) { var result = DbObj.FirstOrDefault(t => t.Id.Equals(ID)); if (result != null) { Remove(result); } } } /// /// 更新信息 /// /// /// public void Update(T obj) { lock (SqliteLock) { var result = DbObj.FirstOrDefault(t => t.Id.Equals(obj.Id)); if (result != null) result.json = obj.json; } } } public class DataVModel { [Key] public string Id { get; set; } public string json { get; set; } } }