gpt4 book ai didi

sqlite - 创建表 Entity Framework Core 和 SQLite

转载 作者:行者123 更新时间:2023-12-03 15:53:53 25 4
gpt4 key购买 nike

使用 Microsoft.EntityFrameworkCore.SQLite,我正在尝试创建数据库的代码级创建,并向表中添加一个简单的行。我得到错误,SQLite 错误:没有这样的表 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));
}
}
}

跳转列表类

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 说明了这一点

Applies any pending migrations for the context to the database.

什么是挂起的迁移?我似乎无法在任何地方找到关于这些的任何文档。

我正在结合以下示例:

编辑:如果我将 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; }

此外,我必须使用 LONG 而不是 INT 作为类 ID,因为 sqlite 使用 LONG 作为表 ID 的默认值,因此在执行 CRUD 操作后它会失败,因为它无法比较/转换/转换 LONG(64) 到INT(32).

关于sqlite - 创建表 Entity Framework Core 和 SQLite,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44224141/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com