作为对 SO 社区和帮助他人的小小感谢,我提供了用于处理架构更改的主要代码。请注意,这将处理从任何早期版本到最新版本的数据库升级(即使用户跳过其间的版本)。不处理数据库降级。我可能应该多做一些错误检查 | try/catch 语句。
在我的 sqlite 助手类中,我有以下声明(注意版本在首次创建数据库时设置为 1):
private SQLiteConnection _db;
// Increment this number whenever DB schema changes are made
private const int LATEST_DATABASE_VERSION = 3;
那么主要的升级方法是:
private void DoUpgradeDb(int oldVersion, int newVersion)
{
for (int vFrom = oldVersion; vFrom < newVersion; vFrom++)
{
switch (vFrom)
{
case 1: // Upgrade from v1 to v2
UpgradeV1AlterPersonAddColumnAge();
break;
case 2: // Upgrade from v2 to v3
UpgradeV2CreateTableHobbies();
break;
default:
break;
}
}
// Save the new version number to local storage
App.AppSettingsService.SetDatabaseVersion(newVersion);
}
正如您在上面看到的,我喜欢将每个版本中所做的单独更改放入自己的方法中,因此我可以将UpgradeV2CreateTableHobbies() 方法定义为:
private void UpgradeV2CreateTableHobbies()
{
_db.CreateTable<Hobbies>();
}
当然,如果数据库是从头开始创建的(例如新安装),您还需要记住进行更改。
当进行下一组架构更改时,您增加 LATEST_DATABASE_VERSION 常量。然后,我检查每次实例化我的 Sqlite 助手类时是否需要版本升级(因为我使用单例模式),您可以执行以下操作:
private bool UpgradeDbIfRequired()
{
bool wasUpgradeApplied = false;
// I wrote a GetDatabaseVersion helper method that reads the version (as nullable int) from the app settings.
int? currentVersion = App.AppSettingsService.GetDatabaseVersion();
if (currentVersion.HasValue && currentVersion.Value < LATEST_DATABASE_VERSION)
{
// Upgrade to latest version
DoUpgradeDb(currentVersion.Value, LATEST_DATABASE_VERSION);
wasUpgradeApplied = true;
}
else
{
// Already on latest version
return false;
}
return wasUpgradeApplied;
}