c# - .net core 上的 sqlite 发布到 azure 失败

标签 c# sqlite azure asp.net-core

我正在尝试将使用 sqlite 的代码优先 Web 应用程序发布到 Azure。现在,该应用程序在本地运行良好。但是当我发布时,似乎数据库文件没有正确创建,并且出现以下错误:

SqliteException: SQLite Error 1: 'no such table: Blogs'. Microsoft.Data.Sqlite.Interop.MarshalEx.ThrowExceptionForRC(int rc, Sqlite3Handle db)

我不确定为什么没有创建博客表(我假设其余的也没有创建)。

我的ApplicationDbContext.cs看起来像这样:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {

    }

    public ApplicationDbContext()
    {
        Database.EnsureCreated();
        Database.Migrate();
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
    }

    public DbSet<Publication> Publications { get; set; }
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Student> Students { get; set; }
    public DbSet<ApplicationUser> ApplicationUser { get; set; }
}

配置:

    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlite(Configuration.GetConnectionString("DefaultConnection"))
        );
    }

appsettings.json中的DefaultConnection:

  "ConnectionStrings": {
    "DefaultConnection": "Filename=.\\mydb.sqlite"
  },

此外,当我下载 mydb.sqlite 并打开它时,它完全是空的。

最佳答案

@Tseng 您对 EnsureCreated 的直觉是正确的。我最终通过清除构造函数并将其添加到 Startup.cs

Configure 方法的 end 来解决这个问题
    var serviceScopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
    using (var serviceScope = serviceScopeFactory.CreateScope())
    {
        var dbContext = serviceScope.ServiceProvider.GetService<ApplicationDbContext>();
        dbContext.Database.EnsureCreated();
    }

我找到了答案here

关于c# - .net core 上的 sqlite 发布到 azure 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43269405/

相关文章:

c# - 将自定义字段属性添加到 CsvHelper

c# - 如何在 Visual Studio 调试器中查看 C# 自动属性的支持字段?

c# - '无法加载文件或程序集 'System.Web.Helpers' 或其依赖项之一

android - 当我将一个超过 100,000 个索引的 bytearray 存储到 sqlite 中时,当我从表中选择它时,我只能得到它的 20 个索引

c# - ADAL Azure AD 身份验证用户的登录信息从不同的 Azure AD session 缓存

azure - 使用 Azure Powershell 在应用服务环境中创建 Azure 应用服务计划

c# - 在单个 exe 中捆绑 .net exe、dll、.net 环境和 native dll

sql - 复合主键限制?

sql - sqlite根据列条件创建新行

typescript - Azure Functions 可以是 Typescript 中的类吗?