2017-04-07 101 views
0

我試圖發佈一個使用sqlite到Azure的代碼優先的webapp。現在,該應用程序在本地正常工作。但是當我發佈,似乎沒有被正確創建的數據庫文件,我得到以下錯誤:.net核心上的sqlite發佈到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")) 
     ); 
    } 

DefaultConnectionappsettings.json

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

而且,當我下載mydb.sqlite並打開它,它完全空。

+0

您不能運行'EnsureCreated'和'Migrate'與此同時。你必須使用一個或另一個。 'EnsureCreated'每次模型改變時都會創建一個新表格(或者如果還沒有記錄)。遷移始終查看遷移並應用它。但是,如果'EnsureCreated'創建DB'Migrate',則通常會失敗,因爲表已經存在。也不要在構造函數中做這樣的動作,這是一個阻塞操作。構建應該**快速** – Tseng

+0

@Tseng我會盡快測試您的建議,但在我的計算機上這可以工作。這是否有任何理由對天藍色有不同的作用? –

+0

總之,使用只是其中之一沒有任何改變 –

回答

1

@Tseng你的直覺EnsureCreated是正確的。我最終通過清除構造和Startup.cs

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

添加此向Configure方法的解決這個我找到了答案here

相關問題