Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ROPC warnings #4849

Merged
merged 25 commits into from
Nov 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions entity-framework/core/cli/powershell.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ The Package Manager Console (PMC) tools for Entity Framework Core perform design

If you aren't using Visual Studio, we recommend the [EF Core Command-line Tools](xref:core/cli/dotnet) instead. The .NET Core CLI tools are cross-platform and run inside a command prompt.

## Installing the tools
[!INCLUDE [managed-identities-test-non-production](~/core/includes/managed-identities-test-non-production.md)]

## Install the tools

Install the Package Manager Console tools by running the following command in **Package Manager Console**:

Expand Down Expand Up @@ -53,7 +55,7 @@ SHORT DESCRIPTION
<A list of available commands follows, omitted here.>
```

## Using the tools
## Use the tools

Before using the tools:

Expand Down Expand Up @@ -215,7 +217,7 @@ Parameters:

| Parameter | Description |
|:------------------------------------------|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| <nobr>`-Connection <String>`</nobr> | The connection string to the database. For ASP.NET Core 2.x projects, the value can be *name=\<name of connection string>*. In that case the name comes from the configuration sources that are set up for the project. This is a positional parameter and is required. |
| <nobr>`-Connection <String>`</nobr> | The connection string to the database. The value can be *name=\<name of connection string>*. In that case the name comes from the [configuration sources](xref:core/miscellaneous/connection-strings#aspnet-core) that are set up for the project. This is a positional parameter and is required. |
| <nobr>`-Provider <String>`</nobr> | The provider to use. Typically this is the name of the NuGet package, for example: `Microsoft.EntityFrameworkCore.SqlServer`. This is a positional parameter and is required. |
| <nobr>`-OutputDir <String>`</nobr> | The directory to put entity class files in. Paths are relative to the project directory. |
| <nobr>`-ContextDir <String>`</nobr> | The directory to put the `DbContext` file in. Paths are relative to the project directory. |
Expand Down
26 changes: 16 additions & 10 deletions entity-framework/core/dbcontext-configuration/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ uid: core/dbcontext-configuration/index

This article shows basic patterns for initialization and configuration of a <xref:Microsoft.EntityFrameworkCore.DbContext> instance.

[!INCLUDE [managed-identities-test-non-production](~/core/includes/managed-identities-test-non-production.md)]

## The DbContext lifetime

The lifetime of a `DbContext` begins when the instance is created and ends when the instance is [disposed](/dotnet/standard/garbage-collection/unmanaged). A `DbContext` instance is designed to be used for a _single_ [unit-of-work](https://www.martinfowler.com/eaaCatalog/unitOfWork.html). This means that the lifetime of a `DbContext` instance is usually very short.
Expand All @@ -29,15 +31,17 @@ A typical unit-of-work when using Entity Framework Core (EF Core) involves:

> [!IMPORTANT]
>
> - It is very important to dispose the <xref:Microsoft.EntityFrameworkCore.DbContext> after use. This ensures both that any unmanaged resources are freed, and that any events or other hooks are unregistered so as to prevent memory leaks in case the instance remains referenced.
> - [DbContext is **not thread-safe**](#avoiding-dbcontext-threading-issues). Do not share contexts between threads. Make sure to [await](/dotnet/csharp/language-reference/operators/await) all async calls before continuing to use the context instance.
> - It is important to dispose the <xref:Microsoft.EntityFrameworkCore.DbContext> after use. This ensures any:
> - Unmanaged resources are freed.
> - Events or other hooks are unregistered. Unregistering prevents memory leaks when the instance remains referenced.
> - [DbContext is **Not thread-safe**](#avoiding-dbcontext-threading-issues). Don't share contexts between threads. Make sure to [await](/dotnet/csharp/language-reference/operators/await) all async calls before continuing to use the context instance.
> - An <xref:System.InvalidOperationException> thrown by EF Core code can put the context into an unrecoverable state. Such exceptions indicate a program error and are not designed to be recovered from.

## DbContext in dependency injection for ASP.NET Core

In many web applications, each HTTP request corresponds to a single unit-of-work. This makes tying the context lifetime to that of the request a good default for web applications.

ASP.NET Core applications are [configured using dependency injection](/aspnet/core/fundamentals/startup). EF Core can be added to this configuration using <xref:Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.AddDbContext%2A> in the [`ConfigureServices`](/aspnet/core/fundamentals/startup#the-configureservices-method) method of `Startup.cs`. For example:
ASP.NET Core applications are [configured using dependency injection](/aspnet/core/fundamentals/startup). EF Core can be added to this configuration using <xref:Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.AddDbContext%2A> in `Program.cs`. For example:

<!--
public void ConfigureServices(IServiceCollection services)
Expand All @@ -48,9 +52,10 @@ ASP.NET Core applications are [configured using dependency injection](/aspnet/co
options => options.UseSqlServer("name=ConnectionStrings:DefaultConnection"));
}
-->
[!code-csharp[ConfigureServices](../../../samples/core/Miscellaneous/ConfiguringDbContext/WebApp/Startup.cs?name=ConfigureServices)]

This example registers a `DbContext` subclass called `ApplicationDbContext` as a scoped service in the ASP.NET Core application service provider (a.k.a. the dependency injection container). The context is configured to use the SQL Server database provider and will read the connection string from ASP.NET Core configuration. It typically does not matter _where_ in `ConfigureServices` the call to `AddDbContext` is made.
[!code-csharp[snippet_1](../../../samples/core/Miscellaneous/ConfiguringDbContext/WebApp9/Program9.cs?name=snippet_1)]

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.

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:

Expand All @@ -63,9 +68,10 @@ The `ApplicationDbContext` class must expose a public constructor with a `DbCont
}
}
-->

[!code-csharp[ApplicationDbContext](../../../samples/core/Miscellaneous/ConfiguringDbContext/WebApp/ApplicationDbContext.cs?name=ApplicationDbContext)]

`ApplicationDbContext` can then be used in ASP.NET Core controllers or other services through constructor injection. For example:
`ApplicationDbContext` can be used in ASP.NET Core controllers or other services through constructor injection:

<!--
public class MyController
Expand All @@ -82,13 +88,13 @@ The `ApplicationDbContext` class must expose a public constructor with a `DbCont

The final result is an `ApplicationDbContext` instance created for each request and passed to the controller to perform a unit-of-work before being disposed when the request ends.

Read further in this article to learn more about configuration options. In addition, see [App startup in ASP.NET Core](/aspnet/core/fundamentals/startup) and [Dependency injection in ASP.NET Core](/aspnet/core/fundamentals/dependency-injection) for more information on configuration and dependency injection in ASP.NET Core.
Read further in this article to learn more about configuration options. See [Dependency injection in ASP.NET Core](/aspnet/core/fundamentals/dependency-injection) for more information.

<!-- See also [Using Dependency Injection](TODO) for advanced dependency injection configuration with EF Core. -->

## Simple DbContext initialization with 'new'
## Basic DbContext initialization with 'new'

`DbContext` instances can be constructed in the normal .NET way, for example with `new` in C#. Configuration can be performed by overriding the `OnConfiguring` method, or by passing options to the constructor. For example:
`DbContext` instances can be constructed with `new` in C#. Configuration can be performed by overriding the `OnConfiguring` method, or by passing options to the constructor. For example:

<!--
public class ApplicationDbContext : DbContext
Expand Down Expand Up @@ -145,7 +151,7 @@ The `DbContextOptions` can be created and the constructor can be called explicit
-->
[!code-csharp[UseNewForWebApp](../../../samples/core/Miscellaneous/ConfiguringDbContext/WebApp/UseNewForWebApp.cs?name=UseNewForWebApp)]

## Using a DbContext factory (e.g. for Blazor)
## Use a DbContext factory

Some application types (e.g. [ASP.NET Core Blazor](/aspnet/core/blazor/)) use dependency injection but do not create a service scope that aligns with the desired `DbContext` lifetime. Even where such an alignment does exist, the application may need to perform multiple units-of-work within this scope. For example, multiple units-of-work within a single HTTP request.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ author: rick-anderson
ms.author: riande
ms.date: 10/23/2024
ms.topic: include
title: an include file
---
> [!WARNING]
> This article uses a local database that doesn't require the user to be authenticated. Production apps should use the most secure authentication flow available. For more information on authentication for deployed test and production apps, see [Secure authentication flows](xref:security/index#secure-authentication-flows).
> This article uses a local database that doesn't require the user to be authenticated. Production apps should use the most secure authentication flow available. For more information on authentication for deployed test and production apps, see [Secure authentication flows](/aspnet/core/security/#secure-authentication-flows).
2 changes: 1 addition & 1 deletion entity-framework/core/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ While EF Core is good at abstracting many programming details, there are some be
* Find issues in the app that only show up when using a specific versions or edition of the database server.
* Catch breaking changes when upgrading EF Core and other dependencies. For example, adding or upgrading frameworks like ASP.NET Core, OData, or AutoMapper. These dependencies can affect EF Core in unexpected ways.
* Performance and stress testing with representative loads. The naïve usage of some features doesn't scale well. For example, multiple collections Includes, heavy use of lazy loading, conditional queries on non-indexed columns, massive updates and inserts with store-generated values, lack of concurrency handling, large models, inadequate cache policy.
* Security review: For example, handling of connection strings and other secrets, database permissions for non-deployment operation, input validation for raw SQL, encryption for sensitive data.
* Security review: For example, handling of connection strings and other secrets, database permissions for non-deployment operation, input validation for raw SQL, encryption for sensitive data. See [Secure authentication flows](/aspnet/core/security/#secure-authentication-flows) for secure configuration and authentication flow.
* Make sure logging and diagnostics are sufficient and usable. For example, appropriate logging configuration, query tags, and Application Insights.
* Error recovery. Prepare contingencies for common failure scenarios such as version rollback, fallback servers, scale-out and load balancing, DoS mitigation, and data backups.
* Application deployment and migration. Plan out how migrations are going to be applied during deployment; doing it at application start can suffer from concurrency issues and requires higher permissions than necessary for normal operation. Use staging to facilitate recovery from fatal errors during migration. For more information, see [Applying Migrations](xref:core/managing-schemas/migrations/applying).
Expand Down
4 changes: 2 additions & 2 deletions entity-framework/core/managing-schemas/migrations/applying.md
Original file line number Diff line number Diff line change
Expand Up @@ -222,10 +222,10 @@ Options:
| `--no-color` | | Don't colorize output. |
| `--prefix-output` | | Prefix output with level. |

The following example applies migrations to a local SQL Server instance using the specified username and password.
The following example applies migrations to a local SQL Server instance using the specified username and credentials:

```powershell
.\efbundle.exe --connection 'Data Source=(local)\MSSQLSERVER;Initial Catalog=Blogging;User ID=myUsername;Password=myPassword'
.\efbundle.exe --connection 'Data Source=(local)\MSSQLSERVER;Initial Catalog=Blogging;User ID=myUsername;Password={;'$Credential;'here'}'
```

> [!WARNING]
Expand Down
8 changes: 5 additions & 3 deletions entity-framework/core/managing-schemas/scaffolding/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ uid: core/managing-schemas/scaffolding
---
# Scaffolding (Reverse Engineering)

Reverse engineering is the process of scaffolding entity type classes and a `DbContext` class based on a database schema. It can be performed using the `Scaffold-DbContext` command of the EF Core Package Manager Console (PMC) tools or the `dotnet ef dbcontext scaffold` command of the .NET Command-line Interface (CLI) tools.
Reverse engineering is the process of scaffolding entity type classes and a [DbContext](/dotnet/api/microsoft.entityframeworkcore.dbcontext) class based on a database schema. It can be performed using the `Scaffold-DbContext` command of the EF Core Package Manager Console (PMC) tools or the `dotnet ef dbcontext scaffold` command of the .NET Command-line Interface (CLI) tools.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not doing xref links?


> [!NOTE]
> The scaffolding of a `DbContext` and entity types documented here is distinct from the [scaffolding of controllers in ASP.NET Core](/aspnet/mvc/overview/getting-started/introduction/adding-a-controller) using Visual Studio, which is not documented here.
Expand All @@ -27,9 +27,11 @@ Both the PMC and the .NET CLI commands have two required arguments: the connecti

### Connection string

The first argument to the command is a connection string to the database. The tools will use this connection string to read the database schema.
[!INCLUDE [managed-identities-test-non-production](~/core/includes/managed-identities-test-non-production.md)]

How you quote and escape the connection string depends on which shell you are using to execute the command; refer to your shell's documentation for more information. For example, PowerShell requires you to escape the `$` character, but not `\`.
The first argument to the command is a connection string to the database. The tools use this connection string to read the database schema.

How the connection string is quoted and escaped depends on the shell that is used to run the command. Refer to the shell's documentation. For example, PowerShell requires escaping `$`, but not `\`.

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.

Expand Down
2 changes: 2 additions & 0 deletions entity-framework/core/miscellaneous/multitenancy.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ uid: core/miscellaneous/multitenancy

Many line of business applications are designed to work with multiple customers. It is important to secure the data so that customer data isn't "leaked" or seen by other customers and potential competitors. These applications are classified as "multi-tenant" because each customer is considered a tenant of the application with their own set of data.

[!INCLUDE [managed-identities-test-non-production](~/core/includes/managed-identities-test-non-production.md)]

> [!IMPORTANT]
> This document provides examples and solutions "as is." These are not intended to be "best practices" but rather "working practices" for your consideration.

Expand Down
11 changes: 10 additions & 1 deletion entity-framework/ef6/fundamentals/configuring/config-file.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,16 @@ ms.date: 10/23/2016
uid: ef6/fundamentals/configuring/config-file
---
# Configuration File Settings
Entity Framework allows a number of settings to be specified from the configuration file. In general EF follows a ‘convention over configuration’ principle: all the settings discussed in this post have a default behavior, you only need to worry about changing the setting when the default no longer satisfies your requirements.
Entity Framework allows a number of settings to be specified from the configuration file. In general EF follows a ‘convention over configuration’ principle: all the settings discussed in this post have a default behavior, you only need to worry about changing the setting when the default no longer satisfies your requirements.

Rick-Anderson marked this conversation as resolved.
Show resolved Hide resolved
## Configuration data guidelines

* Never store passwords or other sensitive data in configuration provider code or in plain text configuration files.
* Don't use production secrets in development or test environments.
* Specify secrets outside of the project so that they can't be accidentally committed to a source code repository.
* Consider protecting the contents of the configuration file using [Protected Configuration](/dotnet/framework/data/adonet/connection-strings-and-configuration-files#encrypt-configuration-file-sections-using-protected-configuration).

Rick-Anderson marked this conversation as resolved.
Show resolved Hide resolved
[!INCLUDE [managed-identities-test-non-production](~/core/includes/managed-identities-test-non-production.md)]

## A Code-Based Alternative

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,15 @@ ms.date: 10/23/2016
uid: ef6/fundamentals/configuring/connection-strings
---
# Connection strings and models
This topic covers how Entity Framework discovers which database connection to use, and how you can change it. Models created with Code First and the EF Designer are both covered in this topic.
This article covers how Entity Framework discovers which database connection to use, and how to change it. Models created with Code First and the EF Designer are covered.

Typically an Entity Framework application uses a class derived from DbContext. This derived class will call one of the constructors on the base DbContext class to control:
[!INCLUDE [managed-identities-test-non-production](~/core/includes/managed-identities-test-non-production.md)]

- How the context will connect to a database — that is, how a connection string is found/used
- Whether the context will use calculate a model using Code First or load a model created with the EF Designer

Typically an Entity Framework application uses a class derived from DbContext. This derived class calls one of the constructors on the base DbContext class to control:

- How the context connects to a database, that is, how a connection string is found and used.
- Whether the context calculates a model using Code First or loads a model created with the EF Designer.
- Additional advanced options

The following fragments show some of the ways the DbContext constructors can be used.
Expand Down
Loading
Loading