[英]In-memory SQLite and database disappearing
我正在使用Nancy為數據庫創建一個api,並且我想針對內存數據庫進行測試/開發。
我在自定義引導程序類中使用我的數據庫類的實例與連接字符串Data Source=:memory:
這反過來又創建了必要的表 - 我已經逐步完成了這一點,我相信這已經發生了。
然后,我使用相同的連接字符串來獲取新連接以加載/保存數據,但即使是簡單的選擇也會出現表不存在的sql錯誤。
在創建和使用具有相同連接字符串的新連接的邏輯中是否存在錯誤?
你需要保持SQLiteConnection
開放,並確保DbContext
不擁有連接。 這樣,當容器處理DbContext
時,連接不會被它關閉。 注意:這僅適用於EF6。 您仍然可以在EF5中傳遞標志,但在上下文被釋放時,上下文仍將關閉連接。
我創建了一個TestBootstrapper
,它從Web項目繼承了工作的Bootstrapper。
作為ConfigureRequestContainer
方法的一部分,我在DbContext
注冊上使用了一個方法工廠, DbContext
都創建一個新的DbContext
,但使用了現有的連接。 如果不這樣做, DbContext
將在您第一次請求后處理,第二個請求將失敗。
public class TestBootstrapper : Bootstrapper
{
private const string ConnectionString = "data source=:memory:;cache=shared;";
private static SQLiteConnection _connection;
private static TestInitializer _initializer = new TestInitializer();
protected override void ConfigureRequestContainer(TinyIoCContainer, NancyContext context)
{
container.Register<Context>((_,__) =>
{
if (_connection == null)
_connection = new SQLiteConnection(ConnectionString);
// The false flag tells the context it does not own the connection, i.e. it cannot close it. (EF6 behaviour only)
var dbContext = new Context(_connection, _initializer, false);
if (_connection.State == ConnectionState.Closed)
_connection.Open();
// I build the DB and seed it here
_initializer.InitializeDatabase(context);
return dbContext;
});
// Additional type registrations
}
// Call this method on a [TearDown]
public static void Cleanup()
{
if (_connection != null && _connection.State == ConnectionState.Open)
_connection.Close();
_connection = null;
}
}
好的,直接來自文檔:
數據庫連接關閉后,數據庫就不再存在。 “
但是,通過在連接字符串中使用cache=shared
,可以解決多個連接問題。
但是,這不是問題的解決方案,因為一旦最后一個連接關閉,數據庫就不再存在。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.