gpt4 book ai didi

c# - 内存数据库中的 SqlLite : CREATE TABLE does not work?

转载 作者:行者123 更新时间:2023-12-02 10:07:01 25 4
gpt4 key购买 nike

在 SqlLite 文件数据库上使用此代码时,它可以正常工作。

using (var ctx = new Test2010Entities())
{
string s = "CREATE TABLE 'Company' ([Id] integer PRIMARY KEY AUTOINCREMENT NOT NULL, varchar(50) NOT NULL);";

ctx.ExecuteStoreCommand(s);

ctx.Companies.AddObject(new Company { Code = "_1" });
ctx.Companies.AddObject(new Company { Code = "_2" });

ctx.SaveChanges();

foreach (var c in ctx.Companies.ToList())
{
Console.WriteLine(c.Code);
}
}


但是在 SqlLite 'In Memory' 数据库 (Data Source=:memory:;Version=3;New=True;) 上运行此代码时,我收到此异常:

Unhandled Exception: System.Data.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SQLite.SQLiteException: SQL logic error or missing database no such table: Company

请注意,这是使用 VS 2010、EF 4.4.0.0 和 sqlite-netFx40-setup-bundle-x86-2010-1.0.84.0 测试的


:::更新:::
正如 Simon Svensson 建议的那样,在任何其他命令之前打开连接确实可以解决问题:ctx.Connection.Open();

最佳答案

当您的 ORM 关闭您的连接并重新打开它时,就会发生这种情况。这会将 sqlite 内存数据库重置为其默认状态;即空。

除非你设置 connection.release_mode = close(默认是 after_transaction

我不熟悉 Entity Framework ,但我希望有类似的设置或使用 DataContext(IDbConnection)构造函数,记录为“如果您提供打开的连接,DataContext 将不会关闭它。”

同一文档还指出“在 System.Transactions 事务中,DataContext 不会打开或关闭连接以避免升级。”这可能是更清洁的解决方案。

使用一些反射器魔术表明它是 SQLiteConnection.Open 调用(通过 SQLite3.Open)sqlite3_open_interop(如果您使用的是 NuGet sqlite 包)。这表明每次调用 SQLiteConnection.Open 时都会得到一个新的空内存数据库。

关于c# - 内存数据库中的 SqlLite : CREATE TABLE does not work?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17477246/

25 4 0