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

Microsoft.EntityFrameworkCore.DbUpdateException:SQLite表存在却提示不存在

问题描述

遇到如下错误:

Microsoft.EntityFrameworkCore.DbUpdateException: '保存实体更改时发生错误。请查看内部异常了解详细信息。
SqliteException: SQLite Error 1: 'no such table: ProductCategories'.'

已确认应用根目录下的数据库中确实存在ProductCategories表。

相关代码

连接字符串配置

public static class DatabaseConfig
{
    public const string ConnectionString = "Filename=InSimDatabase.db";
}

MAUI项目启动文件代码

public static MauiApp CreateMauiApp()
{
    var builder = MauiApp.CreateBuilder();
    builder
        .UseMauiApp<App>()
        .ConfigureFonts(fonts =>
        {
            fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
            fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
        });

    builder.Services.AddDbContext<AppDBContext>(
        options =>
            options.UseSqlite(DatabaseConfig.ConnectionString));

    builder.Services.AddTransient<ProductCategoryViewModel>();

#if DEBUG
    builder.Logging.AddDebug();
#endif

    return builder.Build();
}

数据库验证

数据库中存在ProductCategories表(已通过截图确认)


可能的解决方案
  • 修正数据库路径指向:MAUI中直接使用Filename=InSimDatabase.db会指向应用私有数据目录,而非你认为的项目根目录。可以先打印实际路径验证:

    var dbPath = Path.Combine(FileSystem.AppDataDirectory, "InSimDatabase.db");
    Console.WriteLine(dbPath); // 输出后检查该路径下的数据库是否包含目标表
    

    然后修改连接字符串:

    public const string ConnectionString = $"Filename={Path.Combine(FileSystem.AppDataDirectory, "InSimDatabase.db")}";
    

    如果你的数据库是嵌入到项目中的资源文件,还需要先将其复制到可访问的目录再使用。

  • 检查EF Core实体映射:确认AppDBContext中对应实体的表名映射是否正确,比如是否添加了特性或Fluent API配置:

    // 特性方式
    [Table("ProductCategories")]
    public class ProductCategory { /* 实体属性 */ }
    
    // 或者Fluent API方式
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ProductCategory>().ToTable("ProductCategories");
    }
    
  • 确认迁移已正确应用:如果使用了EF Core迁移,执行以下命令检查并同步:

    dotnet ef migrations list
    dotnet ef database update
    
  • 清理重建项目:删除项目的bin和obj目录,重新生成后运行,避免旧缓存导致的路径或数据库文件不一致问题。

内容的提问来源于stack exchange,提问作者Muhammad Faizan Khan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 08:03:15