Skip to content

Commit 473282b

Browse files
authored
Add documentation for MSBuild integration (#4870)
Clean up connection string documentation Fixes #4700
1 parent fccb854 commit 473282b

File tree

14 files changed

+127
-112
lines changed

14 files changed

+127
-112
lines changed

entity-framework/core/cli/dotnet.md

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
title: EF Core tools reference (.NET CLI) - EF Core
33
description: Reference guide for the Entity Framework Core .NET Core CLI tools
44
author: SamMonoRT
5-
ms.date: 11/15/2021
5+
ms.date: 11/08/2024
66
uid: core/cli/dotnet
77
---
88

@@ -171,18 +171,27 @@ Lists available `DbContext` types.
171171

172172
The [common options](#common-options) are listed above.
173173

174+
<a name="optimize"></a>
175+
174176
## `dotnet ef dbcontext optimize`
175177

176-
Generates a compiled version of the model used by the `DbContext`.
178+
Generates a compiled version of the model used by the `DbContext` and precompiles queries.
177179

178180
See [Compiled models](xref:core/performance/advanced-performance-topics#compiled-models) for more information.
179181

180182
Options:
181183

182-
| Option | Short | Description |
183-
|:-----------------------------------------|:------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
184+
| Option | Short | Description |
185+
|:-----------------------------------------------------|:------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
184186
| <nobr>`--output-dir <PATH>`</nobr> | `-o` | The directory to put files in. Paths are relative to the project directory. |
185187
| <nobr>`--namespace <NAMESPACE>`</nobr> | `-n` | The namespace to use for all generated classes. Defaults to generated from the root namespace and the output directory plus `CompiledModels`. |
188+
| <nobr>`--suffix <SUFFIX>`</nobr> | | The suffix to attach to the name of all the generated files. E.g. `.g` could be used to indicate that these files contain generated code |
189+
| <nobr>`--no-scaffold`</nobr> | | Don't generate a compiled model. This is used when the compiled model has already been generated. |
190+
| <nobr>`--precompile-queries`</nobr> | | Generate precompiled queries. This is required for NativeAOT compilation if the target project contains any queries |
191+
| <nobr>`--nativeaot`</nobr> | | Generate additional code in the compiled model required for NativeAOT compilation and precompiled queries |
192+
193+
> [!NOTE]
194+
> NativeAOT support and precompiled queries are considered experimental in EF 9 and could change dramatically in the next release.
186195
187196
The [common options](#common-options) are listed above.
188197

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
---
2+
title: EF Core MSBuild tasks - EF Core
3+
description: Reference guide for the Entity Framework Core .NET MSBuild tasks
4+
author: AndriySvyryd
5+
ms.date: 11/08/2024
6+
uid: core/cli/msbuild
7+
---
8+
9+
# Entity Framework Core MSBuild integration
10+
11+
Starting with EF 9, you can use an MSBuild task to generate the compiled model and precompiled queries automatically either when the project is built or when it's published. This is mainly intended to be used with NativeAOT publishing.
12+
13+
> [!WARNING]
14+
> NativeAOT support and the MSBuild integration are experimental features, and are not yet suited for production use.
15+
16+
## Installing the tasks
17+
18+
To get started, install the [Microsoft.EntityFrameworkCore.Tasks](https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Tasks) NuGet package. For example:
19+
20+
```dotnetcli
21+
dotnet add package Microsoft.EntityFrameworkCore.Tasks
22+
```
23+
24+
> [!NOTE]
25+
> **Every** project that needs to be compiled with generated files should reference the NuGet package, it is not transitive by default.
26+
27+
## Using the tasks
28+
29+
If the project specifies `<PublishAot>true</PublishAot>` then by default the MSBuild task will generate a compiled model and precompiled queries during publishing. Otherwise, you can set the following properties to control the generation behavior:
30+
31+
| MSBuild property | Description |
32+
|--------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
33+
| EFOptimizeContext | Set to `true` to enable MSBuild integration. |
34+
| EFScaffoldModelStage | Set to `publish`, `build` or `none` to indicate at which stage the compiled model will be generated. Defaults to `publish`. |
35+
| EFPrecompileQueriesStage | Set to `publish`, `build` or `none` to indicate at which stage the precompiled queries will be generated. Defaults to `publish`. |
36+
| DbContextName | The derived `DbContext` class to use. Class name only or fully qualified with namespaces. If this option is omitted, EF Core will perform generation for all context classes in the project. |
37+
| EFTargetNamespace | The namespace to use for all generated classes. If this option is omitted, EF Core will use `$(RootNamespace)`. |
38+
| EFOutputDir | The folder to put the generated files before the project is compiled. If this option is omitted, EF Core will use `$(IntermediateOutputPath)`. |
39+
| EFNullable | Whether nullable reference types will be used in the generated code. If this option is omitted, EF Core will use `$(Nullable)`. |
40+
41+
## Limitations
42+
43+
* A different startup project cannot be specified when using this approach as it would introduce an inverse build dependency. This means that the context project needs to be autosuficient in terms of configuration, so if your app normally configures the context using a host builder in a different project you'd need to [implement _IDesignTimeDbContextFactory&lt;TContext&gt;_](xref:core/cli/dbcontext-creation#from-a-design-time-factory) in the context project.
44+
* Since the project needs to be compilable before the compiled model is generated this approach doesn't support partial method implementations for customization of the compiled model.
45+
* Currently, this will always generate additional code in the compiled model that's required for NativeAOT. If you are not planning to enable NativeAOT then [generate the compiled model using the CLI tools](xref:core/cli/dotnet#optimize).
46+
47+
## Additional resources
48+
49+
* [Compiled models](xref:core/performance/advanced-performance-topics#compiled-models)

entity-framework/core/cli/powershell.md

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
title: EF Core tools reference (Package Manager Console) - EF Core
33
description: Reference guide for the Entity Framework Core Visual Studio Package Manager Console
44
author: SamMonoRT
5-
ms.date: 11/15/2021
5+
ms.date: 11/08/2024
66
uid: core/cli/powershell
77
---
88
# Entity Framework Core tools reference - Package Manager Console in Visual Studio
@@ -185,6 +185,9 @@ Parameters:
185185

186186
The [common parameters](#common-parameters) are listed above.
187187

188+
> [!NOTE]
189+
> The PMC tools currently don't support generating code required for NativeAOT compilation and precompiled queries.
190+
188191
The following example uses the defaults and works if there is only one `DbContext` in the project:
189192

190193
```powershell
@@ -246,7 +249,7 @@ Example that scaffolds only selected tables and creates the context in a separat
246249
Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Tables "Blog","Post" -ContextDir Context -Context BlogContext -ContextNamespace New.Namespace
247250
```
248251

249-
The following example reads the connection string from the project's configuration possibly set using the [Secret Manager tool](/aspnet/core/security/app-secrets#secret-manager).
252+
The following example [reads the connection string using Configuration](xref:core/miscellaneous/connection-strings#aspnet-core).
250253

251254
```powershell
252255
Scaffold-DbContext "Name=ConnectionStrings:Blogging" Microsoft.EntityFrameworkCore.SqlServer

entity-framework/core/dbcontext-configuration/index.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,13 +49,13 @@ ASP.NET Core applications are [configured using dependency injection](/aspnet/co
4949
services.AddControllers();
5050
5151
services.AddDbContext<ApplicationDbContext>(
52-
options => options.UseSqlServer("name=ConnectionStrings:DefaultConnection"));
52+
options => options.UseSqlServer("name=DefaultConnection"));
5353
}
5454
-->
5555

5656
[!code-csharp[snippet_1](../../../samples/core/Miscellaneous/ConfiguringDbContext/WebApp9/Program9.cs?name=snippet_1)]
5757

58-
The preceding code registers `ApplicationDbContext`, a subclass of `DbContext`, as a scoped service in the ASP.NET Core app service provider. The service provider is also known as the dependency injection container. The context is configured to use the SQL Server database provider and reads the connection string from ASP.NET Core configuration.
58+
The preceding code registers `ApplicationDbContext`, a subclass of `DbContext`, as a scoped service in the ASP.NET Core app service provider. The service provider is also known as the dependency injection container. The context is configured to use the SQL Server database provider and reads the connection string from [ASP.NET Core configuration](xref:core/miscellaneous/connection-strings#aspnet-core).
5959

6060
The `ApplicationDbContext` class must expose a public constructor with a `DbContextOptions<ApplicationDbContext>` parameter. This is how context configuration from `AddDbContext` is passed to the `DbContext`. For example:
6161

entity-framework/core/managing-schemas/migrations/applying.md

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
title: Applying Migrations - EF Core
33
description: Strategies for applying schema migrations to production and development databases using Entity Framework Core
44
author: SamMonoRT
5-
ms.date: 11/02/2021
5+
ms.date: 10/29/2024
66
uid: core/managing-schemas/migrations/applying
77
---
88
# Applying Migrations
@@ -117,9 +117,6 @@ The EF command-line tools can be used to apply migrations to a database. While p
117117
* The SQL commands are applied directly by the tool, without giving the developer a chance to inspect or modify them. This can be dangerous in a production environment.
118118
* The .NET SDK and the EF tool must be installed on production servers and requires the project's source code.
119119

120-
> [!NOTE]
121-
> Each migration is applied in its own transaction. See [GitHub issue #22616](https://github.com/dotnet/efcore/issues/22616) for a discussion of possible future enhancements in this area.
122-
123120
### [.NET Core CLI](#tab/dotnet-core-cli)
124121

125122
The following updates your database to the latest migration:

entity-framework/core/managing-schemas/scaffolding/index.md

Lines changed: 3 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ How the connection string is quoted and escaped depends on the shell that is use
3535

3636
The following example scaffolds entity types and a `DbContext` from the `Chinook` database located on the machine's SQL Server LocalDB instance, making use of the `Microsoft.EntityFrameworkCore.SqlServer` database provider.
3737

38-
#### [.NET Core CLI](#tab/dotnet-core-cli)
38+
#### [.NET CLI](#tab/dotnet-core-cli)
3939

4040
```dotnetcli
4141
dotnet ef dbcontext scaffold "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Chinook" Microsoft.EntityFrameworkCore.SqlServer
@@ -49,67 +49,8 @@ Scaffold-DbContext 'Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Chinook'
4949

5050
***
5151

52-
#### User secrets for connection strings
53-
54-
If you have a .NET application that uses the hosting model and configuration system, such as an ASP.NET Core project, then you can use the `Name=<connection-string>` syntax to read the connection string from configuration.
55-
56-
For example, consider an ASP.NET Core application with the following configuration file:
57-
58-
```json
59-
{
60-
"ConnectionStrings": {
61-
"Chinook": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Chinook"
62-
}
63-
}
64-
```
65-
66-
This connection string in the config file can be used to scaffold from a database using:
67-
68-
#### [.NET Core CLI](#tab/dotnet-core-cli)
69-
70-
```dotnetcli
71-
dotnet ef dbcontext scaffold "Name=ConnectionStrings:Chinook" Microsoft.EntityFrameworkCore.SqlServer
72-
```
73-
74-
#### [Visual Studio PMC](#tab/vs)
75-
76-
```powershell
77-
Scaffold-DbContext 'Name=ConnectionStrings:Chinook' Microsoft.EntityFrameworkCore.SqlServer
78-
```
79-
80-
***
81-
82-
However, storing connection strings in configuration files is not a good idea, since it is too easy to accidentally expose them, for example, by pushing to source control. Instead, connection strings should be stored in a secure way, such as using [Azure Key Vault](/azure/key-vault/keys/quick-create-net) or, when working locally, the [Secret Manager tool](/aspnet/core/security/app-secrets#secret-manager), aka "User Secrets".
83-
84-
For example, to use the User Secrets, first remove the connection string from your ASP.NET Core configuration file. Next, initialize User Secrets by executing the following command in the same directory as the ASP.NET Core project:
85-
86-
```dotnetcli
87-
dotnet user-secrets init
88-
```
89-
90-
This command sets up storage on your computer separate from your source code and adds a key for this storage to the project.
91-
92-
Next, store the connection string in user secrets. For example:
93-
94-
```dotnetcli
95-
dotnet user-secrets set ConnectionStrings:Chinook "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Chinook"
96-
```
97-
98-
Now the same command that previous used the named connection string from the config file will instead use the connection string stored in User Secrets. For example:
99-
100-
#### [.NET Core CLI](#tab/dotnet-core-cli)
101-
102-
```dotnetcli
103-
dotnet ef dbcontext scaffold "Name=ConnectionStrings:Chinook" Microsoft.EntityFrameworkCore.SqlServer
104-
```
105-
106-
#### [Visual Studio PMC](#tab/vs)
107-
108-
```powershell
109-
Scaffold-DbContext 'Name=ConnectionStrings:Chinook' Microsoft.EntityFrameworkCore.SqlServer
110-
```
111-
112-
***
52+
> [!TIP]
53+
> You can [use Configuration to store and retrieve the connection string](xref:core/miscellaneous/connection-strings#aspnet-core)
11354
11455
#### Connection strings in the scaffolded code
11556

entity-framework/core/miscellaneous/connection-strings.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ The ASP.NET Core configuration can store connection strings with various provide
2020

2121
* In the `appsettings.Development.json` or `appsettings.json` file.
2222
* In an environment variable
23+
* Using [Azure Key Vault](/azure/key-vault/keys/quick-create-net)
2324
* Using the [Secret Manager tool](/aspnet/core/security/app-secrets#secret-manager)
2425

2526
> [!WARNING]
@@ -30,10 +31,26 @@ For example, the [Secret Manager tool](/aspnet/core/security/app-secrets#secret-
3031
See the [Configuration section of the ASP.NET Core documentation](/aspnet/core/fundamentals/configuration) for more information.
3132

3233
```dotnetcli
34+
dotnet user-secrets init
3335
dotnet user-secrets set ConnectionStrings:YourDatabaseAlias "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=YourDatabase"
36+
```
37+
38+
Then, in scaffolding, use a connection string that consists of `Name=<database-alias>`.
39+
40+
### [.NET Core CLI](#tab/dotnet-core-cli)
41+
42+
```dotnetcli
3443
dotnet ef dbcontext scaffold Name=ConnectionStrings:YourDatabaseAlias Microsoft.EntityFrameworkCore.SqlServer
3544
```
3645

46+
### [Visual Studio PMC](#tab/vs)
47+
48+
```powershell
49+
Scaffold-DbContext 'Name=ConnectionStrings:YourDatabaseAlias' Microsoft.EntityFrameworkCore.SqlServer
50+
```
51+
52+
***
53+
3754
[!INCLUDE [managed-identities-test-non-production](~/core/includes/managed-identities-test-non-production.md)]
3855

3956
The following example shows the connection string stored in `appsettings.json`.

entity-framework/core/performance/nativeaot-and-precompiled-queries.md

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,10 +38,15 @@ C# interceptors are currently an experimental feature, and require a special opt
3838
</PropertyGroup>
3939
```
4040

41-
Finally, the [`Microsoft.EntityFrameworkCore.Tasks`](https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Tasks) package contains MSBuild integration that will perform the query precompilation (and generate the required compiled model) when you publish your application:
41+
Finally, the [`Microsoft.EntityFrameworkCore.Tasks`](https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Tasks) package contains [MSBuild integration](xref:core/cli/msbuild) that will perform the query precompilation (and generate the required compiled model) when you publish your application:
4242

4343
```xml
44-
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="..." />
44+
<ItemGroup>
45+
<PackageReference Include="Microsoft.EntityFrameworkCore.Tasks" Version="9.0.0">
46+
<PrivateAssets>all</PrivateAssets>
47+
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
48+
</PackageReference>
49+
</ItemGroup>
4550
```
4651

4752
You're now ready to publish your EF NativeAOT application:
@@ -50,7 +55,7 @@ You're now ready to publish your EF NativeAOT application:
5055
dotnet publish -r linux-arm64 -c Release
5156
```
5257

53-
This shows publishing a NativeAOT publishing for Linux running on ARM64; [consult this catalog](/dotnet/core/rid-catalog) to find your runtime identifier. If you'd like to generate the interceptors without publishing - for example to examine the generated sources - you can do so via the `net ef dbcontext optimize --precompile-queries --nativeaot` command.
58+
This shows publishing a NativeAOT publishing for Linux running on ARM64; [consult this catalog](/dotnet/core/rid-catalog) to find your runtime identifier. If you'd like to generate the interceptors without publishing - for example to examine the generated sources - you can do so via the `dotnet ef dbcontext optimize --precompile-queries --nativeaot` command.
5459

5560
Due to the way C# interceptors work, any change in the application source invalidates them and requires repeating the above process. As a result, interceptor generation and actual publishing aren't expected to happen in the inner loop, as the developer is working on code; instead, both `dotnet ef dbcontext optimize` and `dotnet publish` can be executed in a publishing/deployment workflow, in a CI/CD system.
5661

0 commit comments

Comments
 (0)