我正在尝试将使用 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/