處理這類問題的一個好方法是在數據庫中添加一個版本控制系統。 在使用與數據庫的連接之前,只需檢查數據庫中的應用程序版本,並且如果新版本高於前一版本,則運行所有必要的命令來更新數據庫。
例:
public async Task<SQLite.SQLiteConnection> GetSqliteConnectionForUserAsync(string login)
{
using (await _mutex.LockAsync())
{
if (login == null)
{
login = "__anonymous__";
}
SQLite.SQLiteConnection conn;
if (!_userConnections.TryGetValue(login, out conn))
{
conn = new SQLite.SQLiteConnection(Path.Combine(ApplicationData.Current.LocalFolder.Path,
string.Format("{0}.db", Uri.EscapeDataString(login))));
await SqlSchemaHandler.EnsureSchemaReadyAsync(conn, s =>
{
_logger.Info("Schema handler message : {0}", s);
});
_userConnections[login] = conn;
}
return conn;
}
}
和(SqlSchemaHandler):
public static Task EnsureSchemaReadyAsync(SQLiteConnection connection, Action<string> actionReporter)
{
return Task.Run(() =>
{
connection.CreateTable<SchemaInfo>();
var schemaInfo = connection.Table<SchemaInfo>().FirstOrDefault();
if (schemaInfo == null)
{
ApplyV0ToV1(connection);
schemaInfo = new SchemaInfo { Id = 1, Version = 1 };
connection.Insert(schemaInfo);
}
});
}
private static void ApplyV0ToV1(SQLiteConnection connection)
{
connection.CreateTable<Test>();
}
感謝,
[升級應用程序更新數據庫]的可能重複(http://stackoverflow.com/questions/15703352/upgrading-database-on-app-update) –