Skip to content

Instantly share code, notes, and snippets.

@gistlyn
Last active February 11, 2023 04:11
Show Gist options
  • Save gistlyn/db2daf76f823ef733881ec244a8b2173 to your computer and use it in GitHub Desktop.
Save gistlyn/db2daf76f823ef733881ec244a8b2173 to your computer and use it in GitHub Desktop.
Use OrmLite with PostgreSQL
dotnet add package ServiceStack.OrmLite.PostgreSQL
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using ServiceStack;
using ServiceStack.Data;
using ServiceStack.DataAnnotations;
using ServiceStack.OrmLite;
[assembly: HostingStartup(typeof(MyApp.ConfigureDb))]
namespace MyApp;
public class ConfigureDb : IHostingStartup
{
public void Configure(IWebHostBuilder builder) => builder
.ConfigureServices((context, services) => {
services.AddSingleton<IDbConnectionFactory>(new OrmLiteConnectionFactory(
context.Configuration.GetConnectionString("DefaultConnection")
?? "Server=localhost;User Id=test;Password=test;Database=test;Pooling=true;MinPoolSize=0;MaxPoolSize=200",
PostgreSqlDialect.Provider));
})
.ConfigureAppHost(appHost => {
// Enable built-in Database Admin UI at /admin-ui/database
// appHost.Plugins.Add(new AdminDatabaseFeature());
});
}
using MyApp.Migrations;
using ServiceStack;
using ServiceStack.Data;
using ServiceStack.OrmLite;
[assembly: HostingStartup(typeof(MyApp.ConfigureDbMigrations))]
namespace MyApp;
// Code-First DB Migrations: https://docs.servicestack.net/ormlite/db-migrations
public class ConfigureDbMigrations : IHostingStartup
{
public void Configure(IWebHostBuilder builder) => builder
.ConfigureAppHost(afterAppHostInit:appHost => {
var migrator = new Migrator(appHost.Resolve<IDbConnectionFactory>(), typeof(Migration1000).Assembly);
AppTasks.Register("migrate", _ => migrator.Run());
AppTasks.Register("migrate.revert", args => migrator.Revert(args[0]));
AppTasks.Run();
});
}
using ServiceStack.DataAnnotations;
using ServiceStack.OrmLite;
namespace MyApp.Migrations;
public class Migration1000 : MigrationBase
{
public class MyTable
{
[AutoIncrement]
public int Id { get; set; }
public string Name { get; set; }
}
public override void Up()
{
Db.CreateTable<MyTable>();
}
public override void Down()
{
Db.DropTable<MyTable>();
}
}
[
{ "op":"add", "path":"/scripts/postinstall", "value":"dotnet run --AppTasks=migrate" },
{ "op":"add", "path":"/scripts/migrate", "value":"dotnet run --AppTasks=migrate" },
{ "op":"add", "path":"/scripts/revert:last", "value":"dotnet run --AppTasks=migrate.revert:last" },
{ "op":"add", "path":"/scripts/revert:all", "value":"dotnet run --AppTasks=migrate.revert:all" },
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment