EF7(代碼優先)+ SQLite不會為模型創建數據庫和表

entity-framework-core sqlite win-universal-app

我目前正在嘗試重新創建示例,在文檔http://ef.readthedocs.org/en/latest/getting-started/uwp.html中完成 ,使用EF7和SQLite創建通用Windows平台應用程序。

我已經安裝了所需的EF7和EF7 Commands包,並創建了模型和上下文:

 public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
            string dirPath = ApplicationData.Current.LocalFolder.Path;
            string connectionString = "Filename=" + Path.Combine(dirPath, "blogging.db");
            optionsBuilder.UseSqlite(connectionString);
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
    }
}

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public List<Post> Posts { get; set; }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public int BlogId { get; set; }
    public Blog Blog { get; set; }
}

我現在的問題是,在構建解決方案之後,應該支持遷移以為我的模型創建初始表集的命令失敗,但出現以下異常:

 public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
            string dirPath = ApplicationData.Current.LocalFolder.Path;
            string connectionString = "Filename=" + Path.Combine(dirPath, "blogging.db");
            optionsBuilder.UseSqlite(connectionString);
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
    }
}

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public List<Post> Posts { get; set; }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public int BlogId { get; set; }
    public Blog Blog { get; set; }
}

有沒有人有這個問題的解決方案?提前致謝

一般承認的答案

在我的例子中,問題的解決方案是在應用程序啟動之前通過app.xaml中的代碼創建數據庫和表。

using (var db = new BloggingContext())
{
    db.Database.EnsureCreated();
    db.Database.Migrate();
}

上下文+模型:

using (var db = new BloggingContext())
{
    db.Database.EnsureCreated();
    db.Database.Migrate();
}

此外,在訪問數據庫之前,我確保創建它,例如

using (var db = new BloggingContext())
{
    db.Database.EnsureCreated();
    db.Database.Migrate();
}



許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因