You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在.NET项目的SQLite+Entity Framework Core中加载SQLite扩展?

在EF Core中配置SQLite扩展(仅含DLL文件时)

核心思路

EF Core的SQLite提供程序底层基于Microsoft.Data.Sqlite,你可以通过配置DbContext时的扩展选项,获取到底层的SqliteConnection实例,再调用LoadExtension方法加载自定义扩展DLL,和微软官方文档的操作逻辑完全一致,只是整合到了EF Core的服务配置流程中。

配置步骤(分.NET版本)

.NET 5及更早版本(Startup.cs)

在ConfigureServices方法中配置DbContext时,通过UseSqlite的回调监听连接状态,在连接打开后加载扩展:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<YourDbContext>(options =>
    {
        options.UseSqlite("Data Source=your-database.db", sqliteOptions =>
        {
            sqliteOptions.ConfigureConnection(conn =>
            {
                conn.StateChange += (sender, args) =>
                {
                    if (args.CurrentState == System.Data.ConnectionState.Open)
                    {
                        var sqliteConn = (Microsoft.Data.Sqlite.SqliteConnection)sender;
                        // 替换为你的扩展DLL路径,支持相对或绝对路径
                        sqliteConn.LoadExtension("your-extension.dll");
                    }
                };
            });
        });
    });
}

.NET 6+(Program.cs 顶级语句)

在配置DbContext服务时执行相同逻辑:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDbContext<YourDbContext>(options =>
{
    options.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection"), sqliteOptions =>
    {
        sqliteOptions.ConfigureConnection(conn =>
        {
            conn.StateChange += (sender, args) =>
            {
                if (args.CurrentState == System.Data.ConnectionState.Open)
                {
                    var sqliteConn = (Microsoft.Data.Sqlite.SqliteConnection)sender;
                    sqliteConn.LoadExtension("your-extension.dll");
                }
            };
        });
    });
});

var app = builder.Build();
// ... 其他中间件配置

关键注意事项

  • 架构匹配:确保扩展DLL的架构(x86/x64/AnyCPU)与你的应用一致,否则会加载失败。
  • 复制DLL到输出目录:在项目中添加扩展DLL后,右键设置其属性为复制到输出目录 -> 如果较新则复制,或在项目文件中添加:
    <ItemGroup>
      <None Update="your-extension.dll">
        <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      </None>
    </ItemGroup>
    
  • 自定义入口点(可选):如果扩展需要指定初始化入口函数,可传入第二个参数,例如:
    sqliteConn.LoadExtension("your-extension.dll", "sqlite3_custom_extension_init");
    

内容的提问来源于stack exchange,提问作者Paul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 09:52:39