Skip to content

Commit b263767

Browse files
alexwolfmsftrwestMSFT
authored andcommitted
Update .NET passwordless flow
update tabs simplify code
1 parent 9864882 commit b263767

File tree

1 file changed

+83
-64
lines changed

1 file changed

+83
-64
lines changed

azure-sql/database/azure-sql-dotnet-entity-framework-core-quickstart.md

Lines changed: 83 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,12 @@ This quickstart describes how to connect an application to a database in Azure S
2323

2424
- An [Azure subscription](https://azure.microsoft.com/pricing/purchase-options/azure-account?icid=azurefreeaccountdotnet/).
2525
- A SQL database configured for authentication with Microsoft Entra ID ([formerly Azure Active Directory](/entra/fundamentals/new-name)). You can create one using the [Create database quickstart](./single-database-create-quickstart.md).
26-
- [.NET 7.0](https://dotnet.microsoft.com/download) or later.
26+
- [.NET 9.0](https://dotnet.microsoft.com/download) or later.
2727
- [Visual Studio](https://visualstudio.microsoft.com/vs/) or later with the **ASP.NET and web development** workload.
2828
- The latest version of the [Azure CLI](/cli/azure/get-started-with-azure-cli).
2929
- The latest version of the Entity Framework Core tools:
30-
* Visual Studio users should install the [Package Manager Console tools for Entity Framework Core](/ef/core/cli/powershell).
31-
* .NET CLI users should install the [.NET CLI tools for Entity Framework Core](/ef/core/cli/dotnet).
30+
- Visual Studio users should install the [Package Manager Console tools for Entity Framework Core](/ef/core/cli/powershell).
31+
- .NET CLI users should install the [.NET CLI tools for Entity Framework Core](/ef/core/cli/dotnet).
3232

3333
## Configure the database server
3434

@@ -46,7 +46,7 @@ The steps in this section create a .NET Minimal Web API by using either the .NET
4646

4747
1. For the **Project Name**, enter *DotNetSQL*. Leave the default values for the rest of the fields and select **Next**.
4848

49-
1. For the **Framework**, select .NET 7.0 and uncheck **Use controllers (uncheck to use minimal APIs)**. This quickstart uses a Minimal API template to streamline endpoint creation and configuration.
49+
1. For the **Framework**, select .NET 9.0 and uncheck **Use controllers**. This quickstart uses a Minimal API template to streamline endpoint creation and configuration.
5050

5151
1. Choose **Create**. The new project opens inside the Visual Studio environment.
5252

@@ -76,15 +76,7 @@ To connect to Azure SQL Database by using .NET and Entity Framework Core, you ne
7676
- **Microsoft.EntityFrameworkCore.SqlServer**: Provides extra components to connect to the logical server
7777
- **Microsoft.EntityFrameworkCore.Design**: Provides support for running Entity Framework migrations
7878
- **Microsoft.EntityFrameworkCore.Tools**: Provides support for Visual Studio Package Manager Console tooling (PowerShell only)
79-
80-
Alternatively, you can also run the `Install-Package` cmdlet in the **Package Manager Console** window:
81-
82-
```powershell
83-
Install-Package Microsoft.EntityFrameworkCore
84-
Install-Package Microsoft.EntityFrameworkCore.SqlServer
85-
Install-Package Microsoft.EntityFrameworkCore.Design
86-
Install-Package Microsoft.EntityFrameworkCore.Tools
87-
```
79+
- **Swashbuckle.AspNetCore**: Optional - provides support for SwaggerUI interaction with the app endpoints
8880

8981
## [.NET CLI](#tab/dotnet-cli)
9082

@@ -94,6 +86,7 @@ Use the `dotnet add package` command to install the following packages:
9486
dotnet add package Microsoft.EntityFrameworkCore
9587
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
9688
dotnet add package Microsoft.EntityFrameworkCore.Design
89+
dotnet add package Swashbuckle.AspNetCore
9790
```
9891

9992
---
@@ -106,12 +99,7 @@ The Entity Framework Core libraries rely on the `Microsoft.Data.SqlClient` and `
10699

107100
Complete the following steps to connect to Azure SQL Database using Entity Framework Core and the underlying `DefaultAzureCredential` class:
108101

109-
1. Add a `ConnectionStrings` section to the `appsettings.Development.json` file so that it matches the following code. Remember to update the `<your database-server-name>` and `<your-database-name>` placeholders.
110-
111-
The passwordless connection string includes a configuration value of `Authentication=Active Directory Default`, which enables Entity Framework Core to use `DefaultAzureCredential` to connect to Azure services. When the app runs locally, it authenticates with the user you're signed into Visual Studio with. Once the app deploys to Azure, the same code discovers and applies the managed identity that is associated with the hosted app, which you'll configure later.
112-
113-
> [!NOTE]
114-
> Passwordless connection strings are safe to commit to source control, since they do not contain any secrets such as usernames, passwords, or access keys.
102+
1. Add a `ConnectionStrings` section to the `appsettings.Development.json` file so that it matches the following code.
115103

116104
```json
117105
{
@@ -128,49 +116,61 @@ Complete the following steps to connect to Azure SQL Database using Entity Frame
128116
}
129117
```
130118

131-
1. Add the following code to the `Program.cs` file above the line of code that reads `var app = builder.Build();`. This code performs the following configurations:
132-
133-
* Retrieves the passwordless database connection string from the `appsettings.Development.json` file for local development, or from the environment variables for hosted production scenarios.
134-
* Registers the Entity Framework Core `DbContext` class with the .NET dependency injection container.
135-
136-
```csharp
137-
var connection = String.Empty;
138-
if (builder.Environment.IsDevelopment())
139-
{
140-
builder.Configuration.AddEnvironmentVariables().AddJsonFile("appsettings.Development.json");
141-
connection = builder.Configuration.GetConnectionString("AZURE_SQL_CONNECTIONSTRING");
142-
}
143-
else
144-
{
145-
connection = Environment.GetEnvironmentVariable("AZURE_SQL_CONNECTIONSTRING");
146-
}
119+
> [!NOTE]
120+
> Remember to update the `<your database-server-name>` and `<your-database-name>` placeholders in the database connection string. Passwordless connection strings are safe to commit to source control, since they do not contain any secrets such as usernames, passwords, or access keys.
147121

148-
builder.Services.AddDbContext<PersonDbContext>(options =>
149-
options.UseSqlServer(connection));
150-
```
122+
The passwordless connection string includes a configuration value of `Authentication=Active Directory Default`, which enables Entity Framework Core to use `DefaultAzureCredential` to connect to Azure services. When the app runs locally, it authenticates with the user you're signed into Visual Studio with. Once the app deploys to Azure, the same code discovers and applies the managed identity that is associated with the hosted app, which you'll configure later.
151123

152-
1. Add the following endpoints to the bottom of the `Program.cs` file above `app.Run()` to retrieve and add entities in the database using the `PersonDbContext` class.
124+
1. Replace the contents of the `Program.cs` file with the following code:
153125

154126
```csharp
127+
using Microsoft.AspNetCore.Mvc;
128+
using Microsoft.EntityFrameworkCore;
129+
130+
var builder = WebApplication.CreateBuilder();
131+
132+
builder.Services.AddOpenApi();
133+
134+
var connection = String.Empty;
135+
if (builder.Environment.IsDevelopment())
136+
{
137+
builder.Configuration.AddEnvironmentVariables().AddJsonFile("appsettings.Development.json");
138+
connection = builder.Configuration.GetConnectionString("AZURE_SQL_CONNECTIONSTRING");
139+
}
140+
else
141+
{
142+
connection = Environment.GetEnvironmentVariable("AZURE_SQL_CONNECTIONSTRING");
143+
}
144+
145+
builder.Services.AddDbContext<PersonDbContext>(options =>
146+
options.UseSqlServer(connection));
147+
148+
var app = builder.Build();
149+
150+
if (app.Environment.IsDevelopment())
151+
{
152+
app.MapOpenApi();
153+
app.UseSwaggerUI(options =>
154+
{
155+
options.SwaggerEndpoint("/openapi/v1.json", "v1");
156+
});
157+
}
158+
159+
app.MapGet("/", () => "Hello world!");
160+
155161
app.MapGet("/Person", (PersonDbContext context) =>
156162
{
157163
return context.Person.ToList();
158-
})
159-
.WithName("GetPersons")
160-
.WithOpenApi();
164+
});
161165

162166
app.MapPost("/Person", (Person person, PersonDbContext context) =>
163167
{
164168
context.Add(person);
165169
context.SaveChanges();
166-
})
167-
.WithName("CreatePerson")
168-
.WithOpenApi();
169-
```
170+
});
170171

171-
Finally, add the `Person` and `PersonDbContext` classes to the bottom of the `Program.cs` file. The Person class represents a single record in the database's `Persons` table. The `PersonDbContext` class represents the Person database and allows you to perform operations on it through code. You can read more about `DbContext` in the [Getting Started](/ef/core/get-started/overview/first-app) documentation for Entity Framework Core.
172+
app.Run();
172173

173-
```csharp
174174
public class Person
175175
{
176176
public int Id { get; set; }
@@ -189,6 +189,14 @@ Complete the following steps to connect to Azure SQL Database using Entity Frame
189189
}
190190
```
191191

192+
The preceding code handles the following:
193+
194+
- Retrieves the passwordless database connection string from the `appsettings.Development.json` file for local development, or from the environment variables for hosted production scenarios.
195+
- Registers the Entity Framework Core `DbContext` class with the .NET dependency injection container. You can read more about `DbContext` in the [Getting Started](/ef/core/get-started/overview/first-app) documentation for Entity Framework Core.
196+
- Configures .NET 9.0 OpenAPI support with SwaggerUI to provide a UI you can use to interact with the app endpoints and database.
197+
- Adds endpoints to retrieve and add entities in the database.
198+
- Defines a `Person` class to represent a single record in the `Persons` database table, and the `PersonDbContext` class that was registered with the .NET dependency injection container.
199+
192200
## Run the migrations to create the database
193201

194202
To update the database schema to match your data model using Entity Framework Core, you must use a migration. Migrations can create and incrementally update a database schema to keep it in sync with your application's data model. You can learn more about this pattern in the [migrations overview](/ef/core/managing-schemas/migrations).
@@ -252,11 +260,11 @@ The app is ready to be deployed to Azure. Visual Studio can create an Azure App
252260
1. For the specific target, select **Azure App Service (Windows)**, and then select **Next**.
253261
1. Select the green **+** icon to create a new App Service to deploy to and enter the following values:
254262

255-
* **Name**: Leave the default value.
256-
* **Subscription name**: Select the subscription to deploy to.
257-
* **Resource group**: Select **New** and create a new resource group called *msdocs-dotnet-sql*.
258-
* **Hosting Plan**: Select **New** to open the hosting plan dialog. Leave the default values and select **OK**.
259-
* Select **Create** to close the original dialog. Visual Studio creates the App Service resource in Azure.
263+
- **Name**: Leave the default value.
264+
- **Subscription name**: Select the subscription to deploy to.
265+
- **Resource group**: Select **New** and create a new resource group called *msdocs-dotnet-sql*.
266+
- **Hosting Plan**: Select **New** to open the hosting plan dialog. Leave the default values and select **OK**.
267+
- Select **Create** to close the original dialog. Visual Studio creates the App Service resource in Azure.
260268

261269
:::image type="content" source="media/passwordless-connections/create-app-service-small.png" alt-text="Screenshot showing how to deploy with Visual Studio." lightbox="media/passwordless-connections/create-app-service.png":::
262270

@@ -265,7 +273,7 @@ The app is ready to be deployed to Azure. Visual Studio can create an Azure App
265273

266274
1. Select **Publish** in the upper right of the publishing profile summary to deploy the app to Azure.
267275

268-
When the deployment finishes, Visual Studio launches the browser to display the hosted app, but at this point the app doesn't work correctly on Azure. You still need to configure the secure connection between the App Service and the SQL database to retrieve your data.
276+
When the deployment finishes, Visual Studio launches the browser to display the hosted app. You should see the `Hello world` message from the default endpoint. However, at this point the database endpoints will not work correctly on Azure. You still need to configure the secure connection between the App Service and the SQL database to retrieve your data.
269277

270278
## Connect the App Service to Azure SQL Database
271279

@@ -279,17 +287,25 @@ There are multiple tools available to implement these steps:
279287

280288
## [Service Connector (Recommended)](#tab/service-connector)
281289

282-
Service Connector is a tool that streamlines authenticated connections between different services in Azure. Service Connector currently supports connecting an App Service to a SQL database via the Azure CLI using the `az webapp connection create sql` command. This single command completes the three steps mentioned above for you.
290+
Service Connector is a tool that streamlines authenticated connections between different services in Azure. Service Connector currently supports connecting an App Service to a SQL database using the Azure CLI passwordless extension.
283291

284-
```azurecli
285-
az webapp connection create sql
286-
-g <your-resource-group>
287-
-n <your-app-service-name>
288-
--tg <your-database-server-resource-group>
289-
--server <your-database-server-name>
290-
--database <your-database-name>
291-
--system-identity
292-
```
292+
1. Install or upgrade the Service Connector passwordless extension:
293+
294+
```azcli
295+
az extension add --name serviceconnector-passwordless --upgrade
296+
```
297+
298+
1. Run the `az webapp connection create sql` command to connect your web app to the database using a system-assigned managed identity:
299+
300+
```azurecli
301+
az webapp connection create sql
302+
-g <your-resource-group>
303+
-n <your-app-service-name>
304+
--tg <your-database-server-resource-group>
305+
--server <your-database-server-name>
306+
--database <your-database-name>
307+
--system-identity
308+
```
293309

294310
You can verify the changes made by Service Connector on the App Service settings.
295311

@@ -346,6 +362,9 @@ The person you created locally should display in the browser. Congratulations! Y
346362

347363
[!INCLUDE [passwordless-resource-cleanup](../includes/passwordless-resource-cleanup.md)]
348364

365+
> [!NOTE]
366+
> If you deployed the sample app to Azure, make sure to also search for and delete the App Service resource to avoid unintended costs.
367+
349368
## Related content
350369

351370
- [Tutorial: Secure a database in Azure SQL Database](./secure-database-tutorial.md)

0 commit comments

Comments
 (0)