Skip to content

SQLite DbContext

shuxin edited this page Nov 20, 2023 · 3 revisions

创建 DbContext

对于 SQLite 数据库,需要安装 Install-Package Chloe.SQLite 以及 SQLite 的驱动,然后使用 Chloe.SQLite.SQLiteContext 创建上下文实例。注意:DbContext 实例非线程安全,一定要避免多线程同时使用同一个 DbContext 对象。同时,用完务必要将 DbContext 释放。

创建 SQLiteContext:

SQLiteContext context = new SQLiteContext(() =>
{
    IDbConnection conn = new SQLiteConnection("Your connection string");  //需要自己引入数据库驱动
    return conn;
});

ASP.NET CORE 配置 Service:

public void ConfigureServices(IServiceCollection services)
{
    //...
	
    services.AddScoped<Chloe.IDbContext>((serviceProvider) =>
    {
        SQLiteContext context = new SQLiteContext(() =>
        {
            IDbConnection conn = new SQLiteConnection("Your connection string");  //需要自己引入数据库驱动
            return conn;
        });

        return context;
    });
   
    //...
}