我使用SQLite的面前,但我沒能創建使用DataContext
(AFAIK SQLite的不支持),所以我切換到MS SQL CE 4(這是我所知道的是一個數據庫不贊成,但它仍然可以安裝xcopy並且相對較小),但是我在創建數據庫時遇到了問題。MS SQL CE數據庫DataContext的存在/刪除
首先,我試着不打開連接,但DatabaseExists
返回false。我認爲我必須打開連接,所以現在我試圖使用DataContext
的DatabaseExists
和DeleteDatabase
打開連接。我創建像這樣的連接:
SqlCeConnectionStringBuilder stringBuilder = new SqlCeConnectionStringBuilder();
stringBuilder.DataSource = dataSource;
connection = new SqlCeConnection(stringBuilder.ConnectionString);
其中dataSouce
是數據庫的相對名稱。
然後,我試圖使用強類型DataContext
(稱爲Context
)來確定數據庫是否存在並創建,如果它不存在。
protected DBDataProvider(IConnectionProvider connectionProvider)
{
connection = connectionProvider.Connection;
dataContext = new Context(connection);
}
public bool CreateDatabase(bool overwriteIfExists = true)
{
try
{
connection.Open();
if (dataContext.DatabaseExists())
{
if (overwriteIfExists)
dataContext.DeleteDatabase();
else
return false;
}
connection.Close();
}
catch
{
// in this case the database does not exist
// at least with MS SQL CE
}
try
{
dataContext.CreateDatabase();
}
catch (Exception ex)
{
// ...
}
return true;
}
但DatabaseExists
始終返回false。所以我認爲這一定是一個問題,所以在關閉連接後我調用了DeleteDatabase
調用,但沒有任何反應,該文件仍然存在。
try
{
connection.Open();
// removed from here...
connection.Close();
dataContext.DeleteDatabase();
}
而且由於數據庫文件是仍然存在的CreateDatabase
拋出異常:
{System.Data.SqlServerCe.SqlCeException (0x80004005): File already exists. Try using a different database name. [ File name = TestDB.db ] at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.CreateDatabase()
這是bug還是我失去了一些東西?
編輯
創建一個小型測試代碼,我能重現此問題。
- 首次運行:沒問題,數據庫文件被創建。
- 第二次運行:異常,因爲根據數據上下文對象,該數據庫不存在
下面是代碼:
public static class Test
{
[Table(Name="test_table")]
public class TestEntity
{
[Column(Name = "id", IsPrimaryKey = true, IsDbGenerated = true, CanBeNull = false, DbType = "INT NOT NULL IDENTITY")]
public Int32 Id
{
get;
set;
}
[Column(Name = "name", CanBeNull = false, DbType = "NVARCHAR(20) NOT NULL UNIQUE")]
public String Name
{
get;
set;
}
}
[Database(Name = "TestDB")]
public class TestContext : DataContext
{
public Table<TestEntity> Entities
{
get { return base.GetTable<TestEntity>(); }
}
public TestContext(IDbConnection connection)
: base(connection)
{
}
}
public static void TryCreate(string dataSource)
{
IDbConnection connection;
TestContext context;
// create connection
{
SqlCeConnectionStringBuilder stringBuilder = new SqlCeConnectionStringBuilder();
stringBuilder.DataSource = dataSource;
connection = new SqlCeConnection(stringBuilder.ConnectionString);
}
// create context
context = new TestContext(connection);
// create database
if (context.DatabaseExists())
context.DeleteDatabase();
context.CreateDatabase();
}
}
編輯2:
問題的解決使用正確的(sdf)文件擴展名。
您是否嘗試過使用數據庫文件的完整路徑? – ErikEJ
剛剛嘗試過,結果相同。它可能是某種權限問題? – csisy
你如何調用你的CreateDatabase代碼?用一些更簡單的repor代碼就可以了嗎?應該可以使用這樣簡單的代碼:https://msdn.microsoft.com/en-us/library/bb399420(v=vs.110)。aspx – ErikEJ