using SQLite; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace Sln.Iot.Repository { /// /// SQLite异步方法帮助类 /// /// public class SQLiteAsyncHelper where T : new() { private static readonly Lazy> lazy = new Lazy>(() => new SQLiteAsyncHelper()); public static SQLiteAsyncHelper Instance { get { return lazy.Value; } } private readonly string _databasePath = Path.Combine(Environment.CurrentDirectory, "DeltaDatabase.db"); private readonly SQLiteAsyncConnection _connectionAsync; // SQLite连接对象 /// /// 构造函数 /// public SQLiteAsyncHelper() { // 创建SQLite连接对象并打开连接 _connectionAsync = new SQLiteAsyncConnection(_databasePath); _connectionAsync.CreateTableAsync(); // 如果表不存在,则创建该表[不会创建重复的表] } /// /// 数据插入 /// /// 要插入的数据项 /// public async Task InsertAsync(T item) { return await _connectionAsync.InsertAsync(item); } /// /// 数据删除 /// /// 要删除的数据的主键ID /// public async Task DeleteAsync(int id) { return await _connectionAsync.DeleteAsync(id); } /// /// 数据更新 /// /// 要更新的数据项 /// public async Task UpdateAsync(T item) { return await _connectionAsync.UpdateAsync(item); } /// /// 根据条件查询记录 /// /// 查询条件 /// public async Task> QueryAsync(Expression> predExpr) { return await _connectionAsync.Table().Where(predExpr).ToListAsync(); } /// /// 查询所有数据 /// /// public async Task> QueryAllAsync() { return await _connectionAsync.Table().ToListAsync(); } /// /// 根据条件查询单条记录 /// /// 查询条件 /// public async Task QuerySingleAsync(Expression> predExpr) { return await _connectionAsync.Table().Where(predExpr).FirstOrDefaultAsync(); } } }