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

.NET MAUI使用AddDbContext注入SQLite上下文遇SQLite Error 14问题

解决MAUI中EF Core DbContext依赖注入的SQLite Error 14问题

核心原因

直接实例化GlobalDbContext时,代码执行时机较晚,MAUI已完成应用环境初始化,数据库路径能正确解析;而DI注册时AddDbContext的配置代码执行较早,此时应用的文件系统路径还未完全就绪,导致连接字符串中的路径解析错误,触发无法打开数据库文件的异常。

正确的DI配置步骤

1. 动态生成数据库连接字符串

在MauiProgram.cs中,通过MAUI的FileSystem类动态获取数据库文件的完整路径,避免硬编码固定路径:

// 获取应用私有数据目录下的数据库文件路径
var dbPath = Path.Combine(FileSystem.AppDataDirectory, "your_database_name.db3");
var connectionString = $"Data Source={dbPath};";

2. 注册DbContext服务

使用AddDbContext注册上下文,传入动态生成的连接字符串,MAUI中推荐使用默认的Scoped生命周期:

builder.Services.AddDbContext<GlobalDbContext>(options =>
{
    options.UseSqlite(connectionString);
    // 可选:开启日志便于调试路径问题
    // options.LogTo(Console.WriteLine, LogLevel.Information);
});

3. 确保DbContext构造函数正确

GlobalDbContext必须接收DbContextOptions<GlobalDbContext>参数并传递给基类:

public class GlobalDbContext : DbContext
{
    public GlobalDbContext(DbContextOptions<GlobalDbContext> options) : base(options)
    {
        // 可选:按需确保数据库已创建
        // Database.EnsureCreated();
    }

    // 定义你的实体集合
    public DbSet<YourEntity> YourEntities { get; set; }
}

4. 注册并注入ViewModel

确保ViewModel已注册到DI容器,再通过构造函数注入GlobalDbContext:

// 在MauiProgram.cs中注册ViewModel
builder.Services.AddScoped<YourViewModel>();

ViewModel构造函数接收上下文:

public class YourViewModel
{
    private readonly GlobalDbContext _dbContext;

    public YourViewModel(GlobalDbContext dbContext)
    {
        _dbContext = dbContext;
        // 后续可正常使用上下文操作数据库
    }
}

调试技巧

  • 打印DI配置时和直接实例化时的数据库路径,对比是否一致:
    // DI配置处打印
    Console.WriteLine("DI DbPath: " + dbPath);
    // 直接实例化处打印
    var directDbPath = Path.Combine(FileSystem.AppDataDirectory, "your_database_name.db3");
    Console.WriteLine("Direct DbPath: " + directDbPath);
    
  • 开启EF Core日志,查看实际使用的连接字符串,确认路径是否正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 22:07:09