Skip to content

Instantly share code, notes, and snippets.

@Eonasdan
Last active July 14, 2018 14:42
Show Gist options
  • Save Eonasdan/651f678903919e1f4fadac38d09ae033 to your computer and use it in GitHub Desktop.
Save Eonasdan/651f678903919e1f4fadac38d09ae033 to your computer and use it in GitHub Desktop.
SQLite EF Style Migrations
Note: IFileService is not completely necessary unless you’re doing Xamarin Forms and need.
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