public async Task Connect([NotNull] string path) { var isExist = CheckFileExist(path); if (!isExist) { Logger.Log(LogLevel.Info, "Failed to connect to non-database file: {0}", path); return; } DisposeConnection(); LocalDbContext context; try { context = new LocalDbContext(CreateConnection(path)); var exists = context.Database.Exists(); } catch (Exception e) { Logger.Log(LogLevel.Info, "Failed to connect to database file: {0}", path); Logger.Log(LogLevel.Error, e); throw; } await Migrate(context); this.Context = context; this.CurrentDatabasePath = path; DatabaseChanged?.Invoke(this, path); }
private async Task Migrate([NotNull] LocalDbContext context) { var currentVersion = long.Parse(Resources.DatabaseVersion); var databaseVersion = context.GetDatabaseVersion(); if (databaseVersion == currentVersion) { Logger.Log(LogLevel.Info, "Database is actual, no migrations needed"); return; } Logger.Log(LogLevel.Info, $"Starting update from {databaseVersion} to {currentVersion}"); while (currentVersion != databaseVersion) { var migration = _migrations.FirstOrDefault(m => m.From == databaseVersion); if (migration == null) { var message = $"Cannot find suitable migration: from {databaseVersion} to {currentVersion}"; Logger.Log(LogLevel.Error, message); throw new Exception(message); } await migration.Migrate(context); databaseVersion = context.GetDatabaseVersion(); } Logger.Log(LogLevel.Info, "Database is updated"); }
public void CreateAndConnectNewDatabase(string path) { DisposeConnection(); LocalDbContext context; try { context = new LocalDbContext(CreateConnection(path)); var exists = context.Database.Exists(); } catch (Exception e) { Logger.Log(LogLevel.Info, "Failed to connect to database file: {0}", path); Logger.Log(LogLevel.Error, e); throw; } this.Context = context; this.CurrentDatabasePath = path; }
private void DisposeConnection() { if (this.Context == null) { return; } try { this.Context?.Database.Connection.Close(); this.Context?.Dispose(); } catch (Exception e) { Logger.Log(LogLevel.Error, "Cannot dispose context"); Logger.Log(LogLevel.Error, e); } this.Context = null; }