Last active
July 14, 2018 14:42
-
-
Save Eonasdan/651f678903919e1f4fadac38d09ae033 to your computer and use it in GitHub Desktop.
SQLite EF Style Migrations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Note: IFileService is not completely necessary unless you’re doing Xamarin Forms and need. | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ApplicationDbContext : SQLiteConnection | |
{ | |
public ApplicationDbContext(IFileService fileService) : base(fileService.GetLocalFilePath("[db_file].sqlite"), false) | |
{ | |
CreateTable<MigrationHistory>(); | |
CreateTable<[YourTable]>(); | |
RunMigrations(); | |
} | |
private void RunMigrations() | |
{ | |
var typeInfo = typeof(IDbMigration).GetTypeInfo(); | |
var migrations = typeInfo.Assembly.GetLoadableTypes() | |
.Where(x => x.Namespace == typeInfo.Namespace && | |
x.GetTypeInfo().DeclaredConstructors.Any() && | |
typeInfo.IsAssignableFrom(x.GetTypeInfo())) | |
.Select(x => (IDbMigration)Activator.CreateInstance(x, this)) | |
.OrderBy(x => x.Id); | |
if (!migrations.Any()) return; | |
var lastMigration = MigrationHistories().OrderByDescending(x => x.MigrationId).FirstOrDefault(); | |
var found = lastMigration == null; | |
foreach (var dbMigration in migrations) | |
{ | |
if (!found && dbMigration.Name != lastMigration.Name) continue; //skip till we find last ran migration | |
if (!found) //skip found migration | |
{ | |
found = true; | |
continue; | |
} | |
dbMigration.Up(); | |
Insert(new MigrationHistory | |
{ | |
MigrationId = dbMigration.Id, | |
Name = dbMigration.Name | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment