【问题标题】:sqlite on .net core publish to azure fails.net core 上的 sqlite 发布到 azure 失败
【发布时间】:2017-04-07 04:02:16
【问题描述】:

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

SqliteException:SQLite 错误 1:“没有这样的表:博客”。 Microsoft.Data.Sqlite.Interop.MarshalEx.ThrowExceptionForRC(int rc, Sqlite3Handle db)

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

我的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"))
        );
    }

DefaultConnection 中的appsettings.json

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

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

【问题讨论】:

  • 您不能同时运行EnsureCreatedMigrate。您必须使用其中一种。 EnsureCreated 每次更改模型时都会创建一个新表(或者如果还没有 - 不记得了)。 Migrate 始终查看迁移并应用它。但是当EnsureCreated 创建数据库Migrate 通常会失败,因为表已经存在。也不要在构造函数中做这样的动作,这是一个阻塞操作。构造应该快速
  • @Tseng 我会尽快测试你的建议,但在我的电脑上可以。这有什么原因在 azure 上的工作方式不同?
  • 无论如何,只使用其中一个并没有改变任何东西
  • 查看日志,也许你在创建/迁移过程中遇到了异常
  • 没什么,只是2017-04-07T09:15:07 PID[5312] Information DeploymentComplete

标签: c# sqlite azure asp.net-core


【解决方案1】:

@Tseng 你对EnsureCreated 的直觉是对的。我最终通过清除构造函数并将其添加到Startup.csConfigure 方法的end 来解决这个问题@

    var serviceScopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
    using (var serviceScope = serviceScopeFactory.CreateScope())
    {
        var dbContext = serviceScope.ServiceProvider.GetService<ApplicationDbContext>();
        dbContext.Database.EnsureCreated();
    }

我找到了答案here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-22
    • 2019-09-29
    • 2018-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多