Skip to content

Commit

Permalink
Perform migration in the app host in local dev scenarios
Browse files Browse the repository at this point in the history
- Add an executable resource if the database directory does not exist.
  • Loading branch information
davidfowl committed Nov 14, 2024
1 parent 9d10860 commit 09ea52d
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 3 deletions.
4 changes: 1 addition & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,8 @@ It showcases:
1. [Install .NET 8](https://dotnet.microsoft.com/en-us/download/dotnet/8.0)

### Database

1. Install the **dotnet-ef** tool: `dotnet tool install dotnet-ef -g`
1. Navigate to the `TodoApi` folder.
1. Run `mkdir .db` to create the local database folder.
1. Run `dotnet ef database update` to create the database.
1. Learn more about [dotnet-ef](https://learn.microsoft.com/en-us/ef/core/cli/dotnet)

### Running the application
Expand Down
8 changes: 8 additions & 0 deletions TodoApi.AppHost/Program.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
var builder = DistributedApplication.CreateBuilder(args);

var migrateOperation = builder.AddTodoDbMigration();

var todoapi = builder.AddProject<Projects.TodoApi>("todoapi");

if (migrateOperation is not null)
{
// Wait for the migration to complete before running the api
todoapi.WaitForCompletion(migrateOperation);
}

builder.AddProject<Projects.Todo_Web_Server>("todo-web-server")
.WithReference(todoapi);

Expand Down
31 changes: 31 additions & 0 deletions TodoApi.AppHost/TodoApiEfMigrationsExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
internal static class TodoApiEfMigrationsExtensions
{
public static IResourceBuilder<ExecutableResource>? AddTodoDbMigration(this IDistributedApplicationBuilder builder)
{
IResourceBuilder<ExecutableResource>? migrateOperation = default;

if (builder.ExecutionContext.IsRunMode)
{
var projectDirectory = Path.GetDirectoryName(new Projects.TodoApi().ProjectPath)!;
var dbDirectory = Path.Combine(projectDirectory, ".db");

if (!Directory.Exists(dbDirectory))
{
Directory.CreateDirectory(dbDirectory);

migrateOperation = builder.AddEfMigration<Projects.TodoApi>("todo-db-migration");
}
}

return migrateOperation;
}

public static IResourceBuilder<ExecutableResource> AddEfMigration<TProject>(this IDistributedApplicationBuilder builder, string name)
where TProject : IProjectMetadata, new()
{
var projectDirectory = Path.GetDirectoryName(new TProject().ProjectPath)!;

// TODO: Support passing a connection string
return builder.AddExecutable(name, "dotnet", projectDirectory, "ef", "database", "update", "--no-build");
}
}

0 comments on commit 09ea52d

Please sign in to comment.