七天.NET 8操作SQLite入门到实战 - 第五天引入SQLite-net ORM并封装常用方法
using SQLite;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace MyApp.Data
{
public class SQLiteNetDataSource
{
private static readonly Lazy<SQLiteAsyncConnection> _lazyInitialization = new Lazy<SQLiteAsyncConnection>(() =>
{
string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "MyApp.db3");
var connection = new SQLiteAsyncConnection(dbPath);
connection.CreateTableAsync().Wait();
return connection;
}, System.Threading.LazyThreadSafetyMode.PublicationOnly);
public static SQLiteAsyncConnection Database => _lazyInitialization.Value;
public static Task<List<T>> GetItemsAsync<T>() where T : new()
{
return Database.Table<T>().ToListAsync();
}
public static async Task<List<T>> GetItemsAsync<T>(Func<T, bool> predicate) where T : new()
{
return await Database.QueryAsync<T>(predicate);
}
public static async Task<T> GetItemAsync<T>(Func<T, bool> predicate) where T : new()
{
var items = await Database.QueryAsync<T>(predicate);
return items.FirstOrDefault();
}
public static Task<int> SaveItemAsync<T>(T item) where T : new()
{
return Database.InsertOrReplaceAsync(item);
}
public static Task<int> DeleteItemAsync<T>(T item) where T : new()
{
return Database.DeleteAsync(item);
}
public static Task<int> DeleteAllItemsAsync<T>() where T : new()
{
return Database.DeleteAllAsync<T>();
}
}
}
这个代码示例展示了如何使用SQLite-net ORM来操作SQLite数据库。代码中定义了一个懒加载的数据库连接,并提供了基本的增删查改操作,包括基于条件的查询。这些操作都是异步的,以避免UI线程的阻塞。这个简单的封装可以被应用中的其他部分用来统一访问数据库。
评论已关闭