[英]Creating table Entity Framework Core and SQLite
我正在尝试使用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()
不能。 我糊涂了。
试试这个(几个月前在一个项目中为我工作,我不记得为什么了):
public virtual DbSet<JumpList> JumpLists { get; set; }
public virtual DbSet<Group> Groups { get; set; }
public virtual DbSet<Item> Items { get; set; }
我也必须对类ID使用LONG而不是INT,因为sqlite使用LONG作为表ID的默认值,因此在执行CRUD操作后,它失败了,因为它无法将LONG(64)比较/转换/广播为INT(32) )。
所以,
Microsoft在制作像样的文档方面遇到了一个严重问题,但是我确实找到了一个站点,该站点的文档有些过时,有关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
是它为您创建的类的名称,并将其InitialDatabases
在项目基础的一个名为Migrations的文件夹中。
现在,当:
context.Database.Migrate();
运行,一切都很好!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.