【发布时间】:2017-10-28 16:18:47
【问题描述】:
使用Microsoft.EntityFrameworkCore.SQLite,我正在尝试创建数据库的代码级创建,并向表中添加一个简单的行。我收到错误消息,SQLite error: no such table Jumplists。
从最后到第一,这里是班级
using JumpList_To_Clipboard.Data.Tables;
using Microsoft.EntityFrameworkCore;
namespace JumpList_To_Clipboard.Data
{
public class DataSQLite : IData
{
public const string DATABASE = "data.sqlite";
public DataSQLite()
{
using (var db = new SQLiteDbContext(DATABASE))
{
// Ensure database is created with all changes to tables applied
db.Database.Migrate();
db.JumpLists.Add(new JumpList { Name = "Default" });
db.SaveChanges(); // Exception thrown here
}
}
}
}
DbContext 类
using JumpList_To_Clipboard.Data.Tables;
using Microsoft.EntityFrameworkCore;
namespace JumpList_To_Clipboard.Data
{
class SQLiteDbContext : DbContext
{
readonly string db_path;
public DbSet<JumpList> JumpLists { get; set; }
public DbSet<Group> Groups { get; set; }
public DbSet<Item> Items { get; set; }
public SQLiteDbContext(string database) : base()
{
db_path = database;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite(string.Format("Data Source={0}", db_path));
}
}
}
JumpList 类
using System.Collections.Generic;
namespace JumpList_To_Clipboard.Data.Tables
{
public class JumpList
{
public int JumpListId { get; set; }
public string Name { get; set; }
public List<Group> Groups { get; set; }
public List<Item> Items { get; set; }
}
}
另外两个类不值得在这里重复,也不要报错。
当我使用 firefox sqlite 扩展查看data.sqlite 文件时,我的三个表都没有列出。
命令db.DataBase.Migrate 这么说
将上下文的所有挂起迁移应用到数据库。
pending migrations 是什么?我似乎在这些的任何地方都找不到任何文档。
我正在结合以下示例:
- https://docs.microsoft.com/en-us/ef/core/get-started/netcore/new-db-sqlite
- https://blogs.msdn.microsoft.com/dotnet/2016/09/29/implementing-seeding-custom-conventions-and-interceptors-in-ef-core-1-0/
编辑:如果我将 db.Database.Migrate(); 替换为 db.Database.EnsureCreated(); 就可以了。从文档中,Migrate() 是相同的,但允许您创建表结构的更新,而 EnsureCreated() 没有。我很困惑。
【问题讨论】:
标签: sqlite entity-framework-core