使用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
?我似乎无法在这些地方找到任何文件。
我正在结合以下的例子:
修改:如果我将db.Database.Migrate();
替换为db.Database.EnsureCreated();
则可行。从文档中,Migrate()
是相同的,但允许您创建表结构的更新,EnsureCreated()
不会。我很困惑。
答案 0 :(得分:0)
试试这个(几个月前在一个项目中为我工作,我不记得为什么):
public virtual DbSet<JumpList> JumpLists { get; set; }
public virtual DbSet<Group> Groups { get; set; }
public virtual DbSet<Item> Items { get; set; }
此外,我必须使用LONG而不是INT作为类ID,因为sqlite使用LONG作为表ID的默认值,因此在执行CRUD操作之后它会失败,因为它无法比较/转换/转换LONG(64) INT(32)。
答案 1 :(得分:0)
所以,
微软在制作体面的文档方面存在严重问题,但我确实找到了一个网站,其Learning Entity Framework Core文档有点过时,特别是链接中的迁移。
在顶部,它提到了,
如果您有Visual Studio,则可以使用程序包管理器控制台(PMC)来管理迁移。
这导致Package Manager Console页面在顶部显示,您需要:
如果要使用程序包管理器控制台执行迁移命令,则需要确保将
Microsoft.EntityFrameworkCore.Tools
文件的最新版本添加到project.json
文件中。
问题是,我的项目(或解决方案)中没有project.json
个文件。经过一些搜索,我发现通过NuGet添加Microsoft.EntityFrameworkCore.Tools
然后通过Tools > NuGet Package Manager > Package Manager Console
我能够运行add-migration InitialDatabases
命令。最后一部分InitialDatabases
是它为您创建的类的名称,并粘贴在项目基础上名为Migrations的文件夹中。
现在时间:
context.Database.Migrate();
运行,一切都很好!