Skip to content

Commit 18c266a

Browse files
Update seeding data article to Aspire 9.3 (#3720)
* Initial corrections. * Updated MySQL and PostgreSQL data seeding sections for Apsire 9.3 * One small correction. * Corrected one code link. * Incorporated feedback from @adegeo.
1 parent b9ea806 commit 18c266a

File tree

8 files changed

+144
-10
lines changed

8 files changed

+144
-10
lines changed

docs/database/seed-database-data.md

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -36,11 +36,11 @@ By default, .NET Aspire database integrations rely on containerized databases, w
3636
3737
## Seed data using SQL scripts
3838

39-
In .NET Aspire 9.2, the recommended method for executing database seeding scripts depends on the database server you use:
39+
The recommended method for executing database seeding scripts depends on the database server you use:
4040

4141
### [SQL Server](#tab/sql-server)
4242

43-
In .NET Aspire 9.2 and later versions, you can use the <xref:Aspire.Hosting.SqlServerBuilderExtensions.WithCreationScript*> method to ensure a T-SQL script is run when the database is created. Add SQL code to this script that creates and populates the database, the necessary tables, and other database objects.
43+
Starting with .NET Aspire 9.2, you can use the <xref:Aspire.Hosting.SqlServerBuilderExtensions.WithCreationScript*> method to ensure a T-SQL script is run when the database is created. Add SQL code to this script that creates and populates the database, the necessary tables, and other database objects.
4444

4545
The following code is an example T-SQL script that creates and populates an address book database:
4646

@@ -56,7 +56,7 @@ Next, in the app host's *AppHost.cs* (or *Program.cs*) file, create the database
5656

5757
:::code source="~/aspire-samples/samples/DatabaseContainers/DatabaseContainers.AppHost/AppHost.cs" range="40-49" :::
5858

59-
This code:
59+
The preceding code:
6060

6161
- Create a SQL Server container by calling `builder.AddSqlServer()`.
6262
- Ensures that data is persisted across debugging sessions by calling `WithDataVolume()` and `WithLifetime(ContainerLifetime.Persistent)`.
@@ -65,7 +65,7 @@ This code:
6565

6666
### [PostgreSQL](#tab/postgresql)
6767

68-
In .NET Aspire 9.2, the `WithCreationScript()` method isn't supported for the PostgreSQL integration. Instead, you must use a bind mount and deploy the setup SQL script to it, so that the data is seeded when the container initializes the database.
68+
Starting with .NET Aspire 9.3, the `WithCreationScript()` method is supported for the PostgreSQL integration but, because there is no `USE DATABASE` in PostgreSQL, it only supports operations against the default database. For example, you can issue `CREATE DATABASE` statements to create other databases, but you can't populate them with tables and data. Instead, you must use a bind mount and deploy the setup SQL script to it, so that the data is seeded when the container initializes the database.
6969

7070
The following code is an example PostgreSQL script that creates and populates a to do list database:
7171

@@ -77,15 +77,21 @@ In the app host's *AppHost.cs* (or *Program.cs*) file, create the database and m
7777

7878
### [MySQL](#tab/mysql)
7979

80-
In .NET Aspire 9.2, the `WithCreationScript()` method isn't supported for the MySQL integration. Instead, you must use a bind mount and deploy the setup SQL script to it, so that the data is seeded when the container initializes the database.
80+
Starting with .NET Aspire 9.3, you can use the <xref:Aspire.Hosting.MySqlBuilderExtensions.WithCreationScript*> method to ensure a MySQL script is run when the database is created. Add SQL code to this script that creates and populates the database, the necessary tables, and other database objects.
8181

82-
The following code is an example MySQL script that creates and populates a product catalog database:
82+
In the following App Host code, the script is created as a string and passed to the `WithCreationScript` method:
8383

84-
:::code source="~/aspire-samples/samples/DatabaseContainers/DatabaseContainers.ApiService/data/mysql/init.sql" :::
84+
:::code source="snippets/mysql-seed-data/AppHost.cs" :::
8585

86-
In the app host's *AppHost.cs* (or *Program.cs*) file, create the database and mount the folder that contains the SQL script as a bind mount:
86+
The preceding code:
87+
88+
- Create a MySQL container by calling `builder.AddMySql()`.
89+
- Uses the `MYSQL_DATABASE` environment variable to name the database `catalog`.
90+
- Ensures that data is persisted across debugging sessions by calling `WithDataVolume()` and `WithLifetime(ContainerLifetime.Persistent)`.
91+
- Create a second container that runs the PHP My Admin user interface for MySQL.
92+
- Calls `WithCreationScript()` to create and seed the database.
8793

88-
:::code source="~/aspire-samples/samples/DatabaseContainers/DatabaseContainers.AppHost/AppHost.cs" range="21-36" :::
94+
If you run this code, you can use the PHP My Admin resource to check that a table called **catalog** has been created and populated with products.
8995

9096
---
9197

@@ -96,7 +102,7 @@ You can also seed data in .NET Aspire projects using EF Core by explicitly runni
96102
> [!IMPORTANT]
97103
> These types of configurations should only be done during development, so make sure to add a conditional that checks your current environment context.
98104
99-
Add the following code to the _:::no-loc text="Program.cs"::: file of your **API Service** project.
105+
Add the following code to the _:::no-loc text="Program.cs":::_ file of your **API Service** project.
100106

101107
### [SQL Server](#tab/sql-server)
102108

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"appHostPath": "../MySQLSeedData.csproj"
3+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
var builder = DistributedApplication.CreateBuilder(args);
2+
3+
var catalogDbName = "catalog";
4+
5+
var mysql = builder.AddMySql("mysql")
6+
.WithEnvironment("MYSQL_DATABASE", catalogDbName)
7+
.WithDataVolume()
8+
.WithLifetime(ContainerLifetime.Persistent)
9+
.WithPhpMyAdmin();
10+
11+
var creationScript = $$"""
12+
USE catalog;
13+
CREATE TABLE IF NOT EXISTS `catalog`
14+
(
15+
`id` int(11) NOT NULL AUTO_INCREMENT,
16+
`name` varchar(255) NOT NULL,
17+
`description` varchar(255) NOT NULL,
18+
`price` DECIMAL(18,2) NOT NULL,
19+
PRIMARY KEY (`id`)
20+
);
21+
22+
-- Insert some sample data into the Catalog table only if the table is empty
23+
INSERT INTO catalog (name, description, price)
24+
SELECT *
25+
FROM (
26+
SELECT '.NET Bot Black Hoodie', 'This hoodie will keep you warm while looking cool and representing .NET!', 19.5 UNION ALL
27+
SELECT '.NET Black & White Mug', 'The perfect place to keep your favorite beverage while you code.', 8.5 UNION ALL
28+
SELECT 'Prism White T-Shirt', "It's a t-shirt, it's white, and it can be yours.", 12
29+
) data
30+
-- This clause ensures the rows are only inserted if the table is empty
31+
WHERE NOT EXISTS (SELECT NULL FROM catalog)
32+
""";
33+
34+
var mysqldb = mysql.AddDatabase(catalogDbName)
35+
.WithCreationScript(creationScript);
36+
37+
builder.Build().Run();
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<Sdk Name="Aspire.AppHost.Sdk" Version="9.3.0" />
4+
5+
<PropertyGroup>
6+
<OutputType>Exe</OutputType>
7+
<TargetFramework>net9.0</TargetFramework>
8+
<ImplicitUsings>enable</ImplicitUsings>
9+
<Nullable>enable</Nullable>
10+
<UserSecretsId>2f0f3679-5f3c-4fe7-957d-ec0d9fabfda4</UserSecretsId>
11+
</PropertyGroup>
12+
13+
<ItemGroup>
14+
<PackageReference Include="Aspire.Hosting.AppHost" Version="9.3.0" />
15+
<PackageReference Include="Aspire.Hosting.MySql" Version="9.3.0" />
16+
</ItemGroup>
17+
18+
</Project>
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
{
2+
"$schema": "https://json.schemastore.org/launchsettings.json",
3+
"profiles": {
4+
"https": {
5+
"commandName": "Project",
6+
"dotnetRunMessages": true,
7+
"launchBrowser": true,
8+
"applicationUrl": "https://localhost:17022;http://localhost:15236",
9+
"environmentVariables": {
10+
"ASPNETCORE_ENVIRONMENT": "Development",
11+
"DOTNET_ENVIRONMENT": "Development",
12+
"ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21048",
13+
"ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22281"
14+
}
15+
},
16+
"http": {
17+
"commandName": "Project",
18+
"dotnetRunMessages": true,
19+
"launchBrowser": true,
20+
"applicationUrl": "http://localhost:15236",
21+
"environmentVariables": {
22+
"ASPNETCORE_ENVIRONMENT": "Development",
23+
"DOTNET_ENVIRONMENT": "Development",
24+
"ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19255",
25+
"ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20128"
26+
}
27+
}
28+
}
29+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"Logging": {
3+
"LogLevel": {
4+
"Default": "Information",
5+
"Microsoft.AspNetCore": "Warning"
6+
}
7+
}
8+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
{
2+
"Logging": {
3+
"LogLevel": {
4+
"Default": "Information",
5+
"Microsoft.AspNetCore": "Warning",
6+
"Aspire.Hosting.Dcp": "Warning"
7+
}
8+
}
9+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
Microsoft Visual Studio Solution File, Format Version 12.00
2+
# Visual Studio Version 17
3+
VisualStudioVersion = 17.5.2.0
4+
MinimumVisualStudioVersion = 10.0.40219.1
5+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MySQLSeedData", "MySQLSeedData.csproj", "{62FFBCD3-B001-5E15-DD62-F84BFCFEA366}"
6+
EndProject
7+
Global
8+
GlobalSection(SolutionConfigurationPlatforms) = preSolution
9+
Debug|Any CPU = Debug|Any CPU
10+
Release|Any CPU = Release|Any CPU
11+
EndGlobalSection
12+
GlobalSection(ProjectConfigurationPlatforms) = postSolution
13+
{62FFBCD3-B001-5E15-DD62-F84BFCFEA366}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
14+
{62FFBCD3-B001-5E15-DD62-F84BFCFEA366}.Debug|Any CPU.Build.0 = Debug|Any CPU
15+
{62FFBCD3-B001-5E15-DD62-F84BFCFEA366}.Release|Any CPU.ActiveCfg = Release|Any CPU
16+
{62FFBCD3-B001-5E15-DD62-F84BFCFEA366}.Release|Any CPU.Build.0 = Release|Any CPU
17+
EndGlobalSection
18+
GlobalSection(SolutionProperties) = preSolution
19+
HideSolutionNode = FALSE
20+
EndGlobalSection
21+
GlobalSection(ExtensibilityGlobals) = postSolution
22+
SolutionGuid = {349C2004-BE30-4CFC-93D4-5995A9408BF3}
23+
EndGlobalSection
24+
EndGlobal

0 commit comments

Comments
 (0)