From c4d9784eec3ed9e535ff3c587a5b10b119e1aa07 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Wed, 23 Oct 2019 13:06:15 +0200 Subject: [PATCH] Run docs through markdown linter Added .markdownlint.json to help keep things clean --- .markdownlint.json | 6 ++ entity-framework/core/extensions/index.md | 6 +- .../core/get-started/install/index.md | 23 ++--- .../core/managing-schemas/index.md | 1 + .../migrations/history-table.md | 1 - .../core/managing-schemas/migrations/index.md | 84 ++++++++++++++----- .../managing-schemas/migrations/projects.md | 12 ++- .../managing-schemas/migrations/providers.md | 14 +++- .../core/managing-schemas/migrations/teams.md | 24 +++--- .../miscellaneous/configuring-dbcontext.md | 11 +-- .../core/miscellaneous/rc2-rtm-upgrade.md | 29 +++---- .../core/miscellaneous/testing/index.md | 5 +- .../core/modeling/data-seeding.md | 4 + .../core/modeling/dynamic-model.md | 1 + .../core/modeling/generated-properties.md | 5 +- entity-framework/core/modeling/inheritance.md | 4 +- entity-framework/core/modeling/keys.md | 2 +- .../core/modeling/owned-entities.md | 10 ++- .../core/modeling/relational/tables.md | 6 +- .../core/modeling/required-optional.md | 4 +- .../core/modeling/table-splitting.md | 2 +- .../core/modeling/value-conversions.md | 14 ++++ .../core/providers/cosmos/index.md | 4 +- .../core/providers/cosmos/limitations.md | 2 +- .../providers/cosmos/unstructured-data.md | 2 +- .../core/providers/in-memory/index.md | 4 +- entity-framework/core/providers/index.md | 5 +- .../core/providers/provider-log.md | 65 +++++++------- .../core/providers/sql-server/index.md | 4 +- .../core/providers/sqlite/index.md | 4 +- .../core/providers/writing-a-provider.md | 3 +- .../core/querying/how-query-works.md | 1 + .../core/querying/related-data.md | 13 ++- entity-framework/core/querying/tags.md | 8 +- .../core/saving/cascade-delete.md | 19 +++-- entity-framework/core/saving/concurrency.md | 8 +- .../core/saving/disconnected-entities.md | 10 ++- .../explicit-values-generated-properties.md | 2 + entity-framework/core/saving/transactions.md | 6 +- .../core/what-is-new/ef-core-1.0.md | 78 ++++++++++++++++- .../core/what-is-new/ef-core-1.1.md | 16 +++- .../core/what-is-new/ef-core-2.0.md | 6 ++ .../core/what-is-new/ef-core-2.1.md | 11 +++ .../core/what-is-new/ef-core-2.2.md | 12 +-- .../ef-core-3.0/breaking-changes.md | 1 + .../core/what-is-new/ef-core-3.0/index.md | 37 ++++---- 46 files changed, 401 insertions(+), 188 deletions(-) create mode 100644 .markdownlint.json diff --git a/.markdownlint.json b/.markdownlint.json new file mode 100644 index 0000000000..cfc3435550 --- /dev/null +++ b/.markdownlint.json @@ -0,0 +1,6 @@ +{ + "default": true, + "MD013": false, + "MD025": { "front_matter_title": "" }, + "MD033": { "allowed_elements": ["sup", "sub", "nobe"] } +} diff --git a/entity-framework/core/extensions/index.md b/entity-framework/core/extensions/index.md index b02ef283c1..f800ccb9e2 100644 --- a/entity-framework/core/extensions/index.md +++ b/entity-framework/core/extensions/index.md @@ -23,7 +23,7 @@ LLBLGen Pro is an entity modeling solution with support for Entity Framework and ### Devart Entity Developer -Entity Developer is a powerful ORM designer for ADO.NET Entity Framework, NHibernate, LinqConnect, Telerik Data Access, and LINQ to SQL. It supports designing EF Core models visually, using model first or database first approaches, and C# or Visual Basic code generation. +Entity Developer is a powerful ORM designer for ADO.NET Entity Framework, NHibernate, LinqConnect, Telerik Data Access, and LINQ to SQL. It supports designing EF Core models visually, using model first or database first approaches, and C# or Visual Basic code generation. [Website](https://www.devart.com/entitydeveloper/) @@ -47,7 +47,7 @@ CatFactory is a scaffolding engine for .NET Core that can automate the generatio ### LoreSoft's Entity Framework Core Generator -Entity Framework Core Generator (efg) is a .NET Core CLI tool that can generate EF Core models from an existing database, much like `dotnet ef dbcontext scaffold`, but it also supports safe code [regeneration](https://efg.loresoft.com/en/latest/regeneration/) via region replacement or by parsing mapping files. This tool supports generating view models, validation, and object mapper code. +Entity Framework Core Generator (efg) is a .NET Core CLI tool that can generate EF Core models from an existing database, much like `dotnet ef dbcontext scaffold`, but it also supports safe code [regeneration](https://efg.loresoft.com/en/latest/regeneration/) via region replacement or by parsing mapping files. This tool supports generating view models, validation, and object mapper code. [Tutorial](https://www.loresoft.com/Generate-ASP-NET-Web-API) [Documentation](https://efg.loresoft.com/en/latest/) @@ -81,7 +81,7 @@ This library allows retrieving the values of primary key (including composite ke ### EntityFrameworkCore.TypedOriginalValues -This library enables strongly typed access to the original values of entity properties. +This library enables strongly typed access to the original values of entity properties. [GitHub repository](https://github.com/NickStrupat/EntityFramework.TypedOriginalValues/) diff --git a/entity-framework/core/get-started/install/index.md b/entity-framework/core/get-started/install/index.md index dde36f5345..76a94dfa6b 100644 --- a/entity-framework/core/get-started/install/index.md +++ b/entity-framework/core/get-started/install/index.md @@ -9,7 +9,7 @@ uid: core/get-started/install/index ## Prerequisites -* EF Core is a [.NET Standard 2.1](/dotnet/standard/net-standard) library. So EF Core requires a .NET implementation that supports .NET Standard 2.1 to run. EF Core can also be referenced by other .NET Standard 2.1 libraries. +* EF Core is a [.NET Standard 2.1](/dotnet/standard/net-standard) library. So EF Core requires a .NET implementation that supports .NET Standard 2.1 to run. EF Core can also be referenced by other .NET Standard 2.1 libraries. * For example, you can use EF Core to develop apps that target .NET Core. Building .NET Core apps requires the [.NET Core SDK](https://dotnet.microsoft.com/download). Optionally, you can also use a development environment like [Visual Studio](https://visualstudio.microsoft.com/vs), [Visual Studio for Mac](https://visualstudio.microsoft.com/vs/mac), or [Visual Studio Code](https://code.visualstudio.com). For more information, check [Getting Started with .NET Core](/dotnet/core/get-started). @@ -58,6 +58,7 @@ For more information, see [NuGet Package Manager Dialog](/nuget/tools/package-ma ``` PowerShell Install-Package Microsoft.EntityFrameworkCore.SqlServer ``` + * To update the provider, use the `Update-Package` command. * To specify a specific version, use the `-Version` modifier. For example, to install EF Core 2.2.0 packages, append `-Version 2.2.0` to the commands @@ -70,7 +71,7 @@ You can install tools to carry out EF Core-related tasks in your project, like c Two sets of tools are available: -* The [.NET Core command-line interface (CLI) tools](xref:core/miscellaneous/cli/dotnet) can be used on Windows, Linux, or macOS. These commands begin with `dotnet ef`. +* The [.NET Core command-line interface (CLI) tools](xref:core/miscellaneous/cli/dotnet) can be used on Windows, Linux, or macOS. These commands begin with `dotnet ef`. * The [Package Manager Console (PMC) tools](xref:core/miscellaneous/cli/powershell) run in Visual Studio on Windows. These commands start with a verb, for example `Add-Migration`, `Update-Database`. @@ -88,28 +89,28 @@ Although you can also use the `dotnet ef` commands from the Package Manager Cons The `dotnet ef` commands are included in current versions of the .NET Core SDK, but to enable the commands on a specific project, you have to install the `Microsoft.EntityFrameworkCore.Design` package: -``` Console -dotnet add package Microsoft.EntityFrameworkCore.Design -``` +``` Console +dotnet add package Microsoft.EntityFrameworkCore.Design +``` For ASP.NET Core apps, this package is included automatically. -> [!IMPORTANT] +> [!IMPORTANT] > Always use the version of the tools package that matches the major version of the runtime packages. ### Get the Package Manager Console tools To get the Package Manager Console tools for EF Core, install the `Microsoft.EntityFrameworkCore.Tools` package. For example, from Visual Studio: -``` PowerShell +``` PowerShell Install-Package Microsoft.EntityFrameworkCore.Tools -``` +``` For ASP.NET Core apps, this package is included automatically. ## Upgrading to the latest EF Core -* Any time we release a new version of EF Core, we also release a new version of the providers that are part of the EF Core project, like Microsoft.EntityFrameworkCore.SqlServer, Microsoft.EntityFrameworkCore.Sqlite, and Microsoft.EntityFrameworkCore.InMemory. You can just upgrade to the new version of the provider to get all the improvements. +* Any time we release a new version of EF Core, we also release a new version of the providers that are part of the EF Core project, like Microsoft.EntityFrameworkCore.SqlServer, Microsoft.EntityFrameworkCore.Sqlite, and Microsoft.EntityFrameworkCore.InMemory. You can just upgrade to the new version of the provider to get all the improvements. * EF Core, together with the SQL Server and the in-memory providers are included in current versions of ASP.NET Core. To upgrade an existing ASP.NET Core application to a newer version of EF Core, always upgrade the version of ASP.NET Core. @@ -122,7 +123,7 @@ For ASP.NET Core apps, this package is included automatically. * Database provider design-time packages such as `Microsoft.EntityFrameworkCore.SqlServer.Design` are no longer required or supported from EF Core 2.0 and later, but aren't automatically removed when upgrading the other packages. * The .NET CLI tools are included in the .NET SDK since version 2.1, so the reference to that package can be removed from the project file: - ```xml + + ``` xml ``` - diff --git a/entity-framework/core/managing-schemas/index.md b/entity-framework/core/managing-schemas/index.md index 72563c19ad..1f74b21b9f 100644 --- a/entity-framework/core/managing-schemas/index.md +++ b/entity-framework/core/managing-schemas/index.md @@ -4,6 +4,7 @@ author: bricelam ms.date: 10/30/2017 --- # Managing Database Schemas + EF Core provides two primary ways of keeping your EF Core model and database schema in sync. To choose between the two, decide whether your EF Core model or the database schema is the source of truth. diff --git a/entity-framework/core/managing-schemas/migrations/history-table.md b/entity-framework/core/managing-schemas/migrations/history-table.md index 63b25840fc..7aa1d03c2e 100644 --- a/entity-framework/core/managing-schemas/migrations/history-table.md +++ b/entity-framework/core/managing-schemas/migrations/history-table.md @@ -5,7 +5,6 @@ ms.author: bricelam ms.date: 11/07/2017 uid: core/managing-schemas/migrations/history-table --- - # Custom Migrations History Table By default, EF Core keeps track of which migrations have been applied to the database by recording them in a table named diff --git a/entity-framework/core/managing-schemas/migrations/index.md b/entity-framework/core/managing-schemas/migrations/index.md index ad1da820a3..95b79816a2 100644 --- a/entity-framework/core/managing-schemas/migrations/index.md +++ b/entity-framework/core/managing-schemas/migrations/index.md @@ -33,14 +33,20 @@ Install the [command-line tools](xref:core/miscellaneous/cli/index): After you've [defined your initial model](xref:core/modeling/index), it's time to create the database. To add an initial migration, run the following command. -``` powershell -Add-Migration InitialCreate -``` +## [.NET Core CLI](#tab/dotnet-core-cli) ``` Console dotnet ef migrations add InitialCreate ``` +## [Visual Studio](#tab/vs) + +``` powershell +Add-Migration InitialCreate +``` + +*** + Three files are added to your project under the **Migrations** directory: * **XXXXXXXXXXXXXX_InitialCreate.cs**--The main migrations file. Contains the operations necessary to apply the migration (in `Up()`) and to revert it (in `Down()`). @@ -56,26 +62,38 @@ The timestamp in the filename helps keep them ordered chronologically so you can Next, apply the migration to the database to create the schema. -``` powershell -Update-Database -``` +## [.NET Core CLI](#tab/dotnet-core-cli) ``` Console dotnet ef database update ``` +## [Visual Studio](#tab/vs) + +``` powershell +Update-Database +``` + +*** + ## Customize migration code After making changes to your EF Core model, the database schema might be out of sync. To bring it up to date, add another migration. The migration name can be used like a commit message in a version control system. For example, you might choose a name like *AddProductReviews* if the change is a new entity class for reviews. -``` powershell -Add-Migration AddProductReviews -``` +## [.NET Core CLI](#tab/dotnet-core-cli) ``` Console dotnet ef migrations add AddProductReviews ``` +## [Visual Studio](#tab/vs) + +``` powershell +Add-Migration AddProductReviews +``` + +*** + Once the migration is scaffolded (code generated for it), review the code for accuracy and add, remove or modify any operations required to apply it correctly. For example, a migration might contain the following operations: @@ -123,14 +141,20 @@ migrationBuilder.DropColumn( Apply the migration to the database using the appropriate command. -``` powershell -Update-Database -``` +## [.NET Core CLI](#tab/dotnet-core-cli) ``` Console dotnet ef database update ``` +## [Visual Studio](#tab/vs) + +``` powershell +Update-Database +``` + +*** + ### Empty migrations Sometimes it's useful to add a migration without making any model changes. In this case, adding a new migration creates code files with empty classes. You can customize this migration to perform operations that don't directly relate to the EF Core model. Some things you might want to manage this way are: @@ -145,40 +169,58 @@ Sometimes it's useful to add a migration without making any model changes. In th Sometimes you add a migration and realize you need to make additional changes to your EF Core model before applying it. To remove the last migration, use this command. -``` powershell -Remove-Migration -``` +## [.NET Core CLI](#tab/dotnet-core-cli) ``` Console dotnet ef migrations remove ``` +## [Visual Studio](#tab/vs) + +``` powershell +Remove-Migration +``` + +*** + After removing the migration, you can make the additional model changes and add it again. ## Revert a migration If you already applied a migration (or several migrations) to the database but need to revert it, you can use the same command to apply migrations, but specify the name of the migration you want to roll back to. -``` powershell -Update-Database LastGoodMigration -``` +## [.NET Core CLI](#tab/dotnet-core-cli) ``` Console dotnet ef database update LastGoodMigration ``` +## [Visual Studio](#tab/vs) + +``` powershell +Update-Database LastGoodMigration +``` + +*** + ## Generate SQL scripts When debugging your migrations or deploying them to a production database, it's useful to generate a SQL script. The script can then be further reviewed for accuracy and tuned to fit the needs of a production database. The script can also be used in conjunction with a deployment technology. The basic command is as follows. -``` powershell -Script-Migration -``` +## [.NET Core CLI](#tab/dotnet-core-cli) ``` Console dotnet ef migrations script ``` +## [Visual Studio](#tab/vs) + +``` powershell +Script-Migration +``` + +*** + There are several options to this command. The **from** migration should be the last migration applied to the database before running the script. If no migrations have been applied, specify `0` (this is the default). diff --git a/entity-framework/core/managing-schemas/migrations/projects.md b/entity-framework/core/managing-schemas/migrations/projects.md index 822917a64e..c653603692 100644 --- a/entity-framework/core/managing-schemas/migrations/projects.md +++ b/entity-framework/core/managing-schemas/migrations/projects.md @@ -40,10 +40,16 @@ To do this... If you did everything correctly, you should be able to add new migrations to the project. -``` powershell -Add-Migration NewMigration -Project MyApp.Migrations -``` +## [.NET Core CLI](#tab/dotnet-core-cli) ``` Console dotnet ef migrations add NewMigration --project MyApp.Migrations ``` + +## [Visual Studio](#tab/vs) + +``` powershell +Add-Migration NewMigration -Project MyApp.Migrations +``` + +*** diff --git a/entity-framework/core/managing-schemas/migrations/providers.md b/entity-framework/core/managing-schemas/migrations/providers.md index 0a4df01606..974f6847ed 100644 --- a/entity-framework/core/managing-schemas/migrations/providers.md +++ b/entity-framework/core/managing-schemas/migrations/providers.md @@ -32,16 +32,22 @@ class MySqliteDbContext : MyDbContext When adding new migration, specify the context types. -``` powershell -Add-Migration InitialCreate -Context MyDbContext -OutputDir Migrations\SqlServerMigrations -Add-Migration InitialCreate -Context MySqliteDbContext -OutputDir Migrations\SqliteMigrations -``` +## [.NET Core CLI](#tab/dotnet-core-cli) ``` Console dotnet ef migrations add InitialCreate --context MyDbContext --output-dir Migrations/SqlServerMigrations dotnet ef migrations add InitialCreate --context MySqliteDbContext --output-dir Migrations/SqliteMigrations ``` +## [Visual Studio](#tab/vs) + +``` powershell +Add-Migration InitialCreate -Context MyDbContext -OutputDir Migrations\SqlServerMigrations +Add-Migration InitialCreate -Context MySqliteDbContext -OutputDir Migrations\SqliteMigrations +``` + +*** + > [!TIP] > You don't need to specify the output directory for subsequent migrations since they are created as siblings to the > last one. diff --git a/entity-framework/core/managing-schemas/migrations/teams.md b/entity-framework/core/managing-schemas/migrations/teams.md index 70dadec7c5..60058952de 100644 --- a/entity-framework/core/managing-schemas/migrations/teams.md +++ b/entity-framework/core/managing-schemas/migrations/teams.md @@ -14,11 +14,13 @@ migration before sharing it. When you merge migrations from your teammates, you may get conflicts in your model snapshot file. If both changes are unrelated, the merge is trivial and the two migrations can coexist. For example, you may get a merge conflict in the customer entity type configuration that looks like this: - <<<<<<< Mine - b.Property("Deactivated"); - ======= - b.Property("LoyaltyPoints"); - >>>>>>> Theirs +``` output +<<<<<<< Mine +b.Property("Deactivated"); +======= +b.Property("LoyaltyPoints"); +>>>>>>> Theirs +``` Since both of these properties need to exist in the final model, complete the merge by adding both properties. In many cases, your version control system may automatically merge such changes for you. @@ -34,11 +36,13 @@ In these cases, your migration and your teammate's migration are independent of Sometimes you encounter a true conflict when merging the model snapshot model. For example, you and your teammate may each have renamed the same property. - <<<<<<< Mine - b.Property("Username"); - ======= - b.Property("Alias"); - >>>>>>> Theirs +``` output +<<<<<<< Mine +b.Property("Username"); +======= +b.Property("Alias"); +>>>>>>> Theirs +``` If you encounter this kind of conflict, resolve it by re-creating your migration. Follow these steps: diff --git a/entity-framework/core/miscellaneous/configuring-dbcontext.md b/entity-framework/core/miscellaneous/configuring-dbcontext.md index b7d6195632..0694dc21ef 100644 --- a/entity-framework/core/miscellaneous/configuring-dbcontext.md +++ b/entity-framework/core/miscellaneous/configuring-dbcontext.md @@ -157,11 +157,12 @@ using (var context = serviceProvider.GetService()) var options = serviceProvider.GetService>(); ``` + ## Avoiding DbContext threading issues Entity Framework Core does not support multiple parallel operations being run on the same `DbContext` instance. This includes both parallel execution of async queries and any explicit concurrent use from multiple threads. Therefore, always `await` async calls immediately, or use separate `DbContext` instances for operations that execute in parallel. -When EF Core detects an attempt to use a `DbContext` instance concurrently, you'll see an `InvalidOperationException` with a message like this: +When EF Core detects an attempt to use a `DbContext` instance concurrently, you'll see an `InvalidOperationException` with a message like this: > A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext, however instance members are not guaranteed to be thread safe. @@ -171,13 +172,13 @@ There are common mistakes that can inadvertently cause concurrent access on the ### Forgetting to await the completion of an asynchronous operation before starting any other operation on the same DbContext -Asynchronous methods enable EF Core to initiate operations that access the database in a non-blocking way. But if a caller does not await the completion of one of these methods, and proceeds to perform other operations on the `DbContext`, the state of the `DbContext` can be, (and very likely will be) corrupted. +Asynchronous methods enable EF Core to initiate operations that access the database in a non-blocking way. But if a caller does not await the completion of one of these methods, and proceeds to perform other operations on the `DbContext`, the state of the `DbContext` can be, (and very likely will be) corrupted. Always await EF Core asynchronous methods immediately. ### Implicitly sharing DbContext instances across multiple threads via dependency injection -The [`AddDbContext`](https://docs.microsoft.com/dotnet/api/microsoft.extensions.dependencyinjection.entityframeworkservicecollectionextensions.adddbcontext) extension method registers `DbContext` types with a [scoped lifetime](https://docs.microsoft.com/aspnet/core/fundamentals/dependency-injection#service-lifetimes) by default. +The [`AddDbContext`](https://docs.microsoft.com/dotnet/api/microsoft.extensions.dependencyinjection.entityframeworkservicecollectionextensions.adddbcontext) extension method registers `DbContext` types with a [scoped lifetime](https://docs.microsoft.com/aspnet/core/fundamentals/dependency-injection#service-lifetimes) by default. This is safe from concurrent access issues in ASP.NET Core applications because there is only one thread executing each client request at a given time, and because each request gets a separate dependency injection scope (and therefore a separate `DbContext` instance). @@ -187,5 +188,5 @@ Using dependency injection, this can be achieved by either registering the conte ## More reading -* Read [Dependency Injection](https://docs.microsoft.com/aspnet/core/fundamentals/dependency-injection) to learn more about using DI. -* Read [Testing](testing/index.md) for more information. +- Read [Dependency Injection](https://docs.microsoft.com/aspnet/core/fundamentals/dependency-injection) to learn more about using DI. +- Read [Testing](testing/index.md) for more information. diff --git a/entity-framework/core/miscellaneous/rc2-rtm-upgrade.md b/entity-framework/core/miscellaneous/rc2-rtm-upgrade.md index 8de6580a11..ac504d8305 100644 --- a/entity-framework/core/miscellaneous/rc2-rtm-upgrade.md +++ b/entity-framework/core/miscellaneous/rc2-rtm-upgrade.md @@ -25,29 +25,22 @@ In RC2, the column definition in a migration looked like `table.Column(n Any existing migrations that were scaffolded prior to using RTM will not have the `maxLength` argument specified. This means the maximum length supported by the database will be used (`nvarchar(max)` on SQL Server). This may be fine for some columns, but columns that are part of a key, foreign key, or index need to be updated to include a maximum length. By convention, 450 is the maximum length used for keys, foreign keys, and indexed columns. If you have explicitly configured a length in the model, then you should use that length instead. -**ASP.NET Identity** +### ASP.NET Identity This change impacts projects that use ASP.NET Identity and were created from a pre-RTM project template. The project template includes a migration used to create the database. This migration must be edited to specify a maximum length of `256` for the following columns. -* **AspNetRoles** - - * Name - - * NormalizedName - -* **AspNetUsers** - - * Email - - * NormalizedEmail - - * NormalizedUserName - - * UserName +* **AspNetRoles** + * Name + * NormalizedName +* **AspNetUsers** + * Email + * NormalizedEmail + * NormalizedUserName + * UserName Failure to make this change will result in the following exception when the initial migration is applied to a database. -```console +``` Console System.Data.SqlClient.SqlException (0x80131904): Column 'NormalizedName' in table 'AspNetRoles' is of a type that is invalid for use as a key column in an index. ``` @@ -72,7 +65,7 @@ If you were targeting .NET Core with RC2, you needed to add `imports` to project Attempting to run EF commands on Universal Windows Platform (UWP) projects results in the following error: -```console +```output System.IO.FileLoadException: Could not load file or assembly 'System.IO.FileSystem.Primitives, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. ``` diff --git a/entity-framework/core/miscellaneous/testing/index.md b/entity-framework/core/miscellaneous/testing/index.md index 181a74e35b..bad4e658f0 100644 --- a/entity-framework/core/miscellaneous/testing/index.md +++ b/entity-framework/core/miscellaneous/testing/index.md @@ -11,5 +11,6 @@ uid: core/miscellaneous/testing/index You may want to test components using something that approximates connecting to the real database, without the overhead of actual database I/O operations. There are two main options for doing this: - * [SQLite in-memory mode](sqlite.md) allows you to write efficient tests against a provider that behaves like a relational database. - * [The InMemory provider](in-memory.md) is a lightweight provider that has minimal dependencies, but does not always behave like a relational database. + +* [SQLite in-memory mode](sqlite.md) allows you to write efficient tests against a provider that behaves like a relational database. +* [The InMemory provider](in-memory.md) is a lightweight provider that has minimal dependencies, but does not always behave like a relational database. diff --git a/entity-framework/core/modeling/data-seeding.md b/entity-framework/core/modeling/data-seeding.md index 834021c501..ef61ca0dcb 100644 --- a/entity-framework/core/modeling/data-seeding.md +++ b/entity-framework/core/modeling/data-seeding.md @@ -11,6 +11,7 @@ uid: core/modeling/data-seeding Data seeding is the process of populating a database with an initial set of data. There are several ways this can be accomplished in EF Core: + * Model seed data * Manual migration customization * Custom initialization logic @@ -53,12 +54,14 @@ Alternatively, you can use `context.Database.EnsureCreated()` to create a new da ### Limitations of model seed data This type of seed data is managed by migrations and the script to update the data that's already in the database needs to be generated without connecting to the database. This imposes some restrictions: + * The primary key value needs to be specified even if it's usually generated by the database. It will be used to detect data changes between migrations. * Previously seeded data will be removed if the primary key is changed in any way. Therefore this feature is most useful for static data that's not expected to change outside of migrations and does not depend on anything else in the database, for example ZIP codes. If your scenario includes any of the following it is recommended to use custom initialization logic described in the last section: + * Temporary data for testing * Data that depends on database state * Data that needs key values to be generated by the database, including entities that use alternate keys as the identity @@ -81,6 +84,7 @@ A straightforward and powerful way to perform data seeding is to use [`DbContext > The seeding code should not be part of the normal app execution as this can cause concurrency issues when multiple instances are running and would also require the app having permission to modify the database schema. Depending on the constraints of your deployment the initialization code can be executed in different ways: + * Running the initialization app locally * Deploying the initialization app with the main app, invoking the initialization routine and disabling or removing the initialization app. diff --git a/entity-framework/core/modeling/dynamic-model.md b/entity-framework/core/modeling/dynamic-model.md index e9ff9c15ae..8f10507637 100644 --- a/entity-framework/core/modeling/dynamic-model.md +++ b/entity-framework/core/modeling/dynamic-model.md @@ -12,6 +12,7 @@ The model built in `OnModelCreating` could use a property on the context to chan [!code-csharp[Main](../../../samples/core/DynamicModel/DynamicContext.cs?name=Class)] ## IModelCacheKeyFactory + However if you tried doing the above without additional changes you would get the same model every time a new context is created for any value of `IgnoreIntProperty`. This is caused by the model caching mechanism EF uses to improve the performance by only invoking `OnModelCreating` once and caching the model. By default EF assumes that for any given context type the model will be the same. To accomplish this the default implementation of `IModelCacheKeyFactory` returns a key that just contains the context type. To change this you need to replace the `IModelCacheKeyFactory` service. The new implementation needs to return an object that can be compared to other model keys using the `Equals` method that takes into account all the variables that affect the model: diff --git a/entity-framework/core/modeling/generated-properties.md b/entity-framework/core/modeling/generated-properties.md index 72eb5b6d1b..eafc2ddfe1 100644 --- a/entity-framework/core/modeling/generated-properties.md +++ b/entity-framework/core/modeling/generated-properties.md @@ -11,6 +11,7 @@ uid: core/modeling/generated-properties ## Value Generation Patterns There are three value generation patterns that can be used for properties: + * No value generation * Value generated on add * Value generated on add or update @@ -40,9 +41,9 @@ Like `value generated on add`, if you specify a value for the property on a newl > [!WARNING] > How the value is generated for added and updated entities will depend on the database provider being used. Database providers may automatically setup value generation for some property types, while others will require you to manually setup how the value is generated. -> +> > For example, when using SQL Server, `byte[]` properties that are set as generated on add or update and marked as concurrency tokens, will be setup with the `rowversion` data type - so that values will be generated in the database. However, if you specify that a `DateTime` property is generated on add or update, then you must setup a way for the values to be generated. One way to do this, is to configure a default value of `GETDATE()` (see [Default Values](relational/default-values.md)) to generate values for new rows. You could then use a database trigger to generate values during updates (such as the following example trigger). -> +> > [!code-sql[Main](../../../samples/core/Modeling/FluentAPI/ValueGeneratedOnAddOrUpdate.sql)] ## Conventions diff --git a/entity-framework/core/modeling/inheritance.md b/entity-framework/core/modeling/inheritance.md index 1864662e92..c2ff6e0e1f 100644 --- a/entity-framework/core/modeling/inheritance.md +++ b/entity-framework/core/modeling/inheritance.md @@ -13,11 +13,11 @@ Inheritance in the EF model is used to control how inheritance in the entity cla By convention, it is up to the database provider to determine how inheritance will be represented in the database. See [Inheritance (Relational Database)](relational/inheritance.md) for how this is handled with a relational database provider. -EF will only setup inheritance if two or more inherited types are explicitly included in the model. EF will not scan for base or derived types that were not otherwise included in the model. You can include types in the model by exposing a *DbSet* for each type in the inheritance hierarchy. +EF will only setup inheritance if two or more inherited types are explicitly included in the model. EF will not scan for base or derived types that were not otherwise included in the model. You can include types in the model by exposing a *DbSet\* for each type in the inheritance hierarchy. [!code-csharp[Main](../../../samples/core/Modeling/Conventions/InheritanceDbSets.cs?highlight=3-4&name=Model)] -If you don't want to expose a *DbSet* for one or more entities in the hierarchy, you can use the Fluent API to ensure they are included in the model. +If you don't want to expose a *DbSet\* for one or more entities in the hierarchy, you can use the Fluent API to ensure they are included in the model. And if you don't rely on conventions, you can specify the base type explicitly using `HasBaseType`. [!code-csharp[Main](../../../samples/core/Modeling/Conventions/InheritanceModelBuilder.cs?highlight=7&name=Context)] diff --git a/entity-framework/core/modeling/keys.md b/entity-framework/core/modeling/keys.md index 367a742ef7..8eebd3ba75 100644 --- a/entity-framework/core/modeling/keys.md +++ b/entity-framework/core/modeling/keys.md @@ -7,7 +7,7 @@ uid: core/modeling/keys --- # Keys (primary) -A key serves as the primary unique identifier for each entity instance. When using a relational database this maps to the concept of a *primary key*. You can also configure a unique identifier that is not the primary key (see [Alternate Keys](alternate-keys.md) for more information). +A key serves as the primary unique identifier for each entity instance. When using a relational database this maps to the concept of a *primary key*. You can also configure a unique identifier that is not the primary key (see [Alternate Keys](alternate-keys.md) for more information). One of the following methods can be used to setup/create a primary key. diff --git a/entity-framework/core/modeling/owned-entities.md b/entity-framework/core/modeling/owned-entities.md index d19817822d..e7f1ed5457 100644 --- a/entity-framework/core/modeling/owned-entities.md +++ b/entity-framework/core/modeling/owned-entities.md @@ -8,7 +8,7 @@ uid: core/modeling/owned-entities --- # Owned Entity Types ->[!NOTE] +> [!NOTE] > This feature is new in EF Core 2.0. EF Core allows you to model entity types that can only ever appear on navigation properties of other entity types. These are called _owned entity types_. The entity containing an owned entity type is its _owner_. @@ -35,7 +35,7 @@ If the `ShippingAddress` property is private in the `Order` type, you can use th [!code-csharp[OwnsOneString](../../../samples/core/Modeling/OwnedEntities/OwnedEntityContext.cs?name=OwnsOneString)] -See the [full sample project](https://github.com/aspnet/EntityFramework.Docs/tree/master/samples/core/Modeling/OwnedEntities) for more context. +See the [full sample project](https://github.com/aspnet/EntityFramework.Docs/tree/master/samples/core/Modeling/OwnedEntities) for more context. ## Implicit keys @@ -53,6 +53,7 @@ To configure a collection of owned types use `OwnsMany` in `OnModelCreating`. Owned types need a primary key. If there are no good candidates properties on the .NET type, EF Core can try to create one. However, when owned types are defined through a collection, it isn't enough to just create a shadow property to act as both the foreign key into the owner and the primary key of the owned instance, as we do for `OwnsOne`: there can be multiple owned type instances for each owner, and hence the key of the owner isn't enough to provide a unique identity for each owned instance. The two most straightforward solutions to this are: + - Defining a surrogate primary key on a new property independent of the foreign key that points to the owner. The contained values would need to be unique across all owners (e.g. if Parent {1} has Child {1}, then Parent {2} cannot have Child {1}), so the value doesn't have any inherent meaning. Since the foreign key is not part of the primary key its values can be changed, so you could move a child from one parent to another one, however this usually goes against aggregate semantics. - Using the foreign key and an additional property as a composite key. The additional property value now only needs to be unique for a given parent (so if Parent {1} has Child {1,1} then Parent {2} can still have Child {2,1}). By making the foreign key part of the primary key the relationship between the owner and the owned entity becomes immutable and reflects aggregate semantics better. This is what EF Core does by default. @@ -83,7 +84,7 @@ You can use the `HasColumnName` method to rename those columns: An owned entity type can be of the same .NET type as another owned entity type, therefore the .NET type may not be enough to identify an owned type. -In those cases, the property pointing from the owner to the owned entity becomes the _defining navigation_ of the owned entity type. From the perspective of EF Core, the defining navigation is part of the type's identity alongside the .NET type. +In those cases, the property pointing from the owner to the owned entity becomes the _defining navigation_ of the owned entity type. From the perspective of EF Core, the defining navigation is part of the type's identity alongside the .NET type. For example, in the following class `ShippingAddress` and `BillingAddress` are both of the same .NET type, `StreetAddress`: @@ -128,14 +129,17 @@ When querying the owner the owned types will be included by default. It is not n Some of these limitations are fundamental to how owned entity types work, but some others are restrictions that we may be able to remove in future releases: ### By-design restrictions + - You cannot create a `DbSet` for an owned type - You cannot call `Entity()` with an owned type on `ModelBuilder` ### Current shortcomings + - Inheritance hierarchies that include owned entity types are not supported - Reference navigations to owned entity types cannot be null unless they are explicitly mapped to a separate table from the owner - Instances of owned entity types cannot be shared by multiple owners (this is a well-known scenario for value objects that cannot be implemented using owned entity types) ### Shortcomings in previous versions + - In EF Core 2.0, navigations to owned entity types cannot be declared in derived entity types unless the owned entities are explicitly mapped to a separate table from the owner hierarchy. This limitation has been removed in EF Core 2.1 - In EF Core 2.0 and 2.1 only reference navigations to owned types were supported. This limitation has been removed in EF Core 2.2 diff --git a/entity-framework/core/modeling/relational/tables.md b/entity-framework/core/modeling/relational/tables.md index dea53b250e..820d2f4f27 100644 --- a/entity-framework/core/modeling/relational/tables.md +++ b/entity-framework/core/modeling/relational/tables.md @@ -22,8 +22,7 @@ You can use Data Annotations to configure the table that a type maps to. ``` csharp using System.ComponentModel.DataAnnotations.Schema; -``` -``` csharp + [Table("blogs")] public class Blog { @@ -49,8 +48,7 @@ You can use the Fluent API to configure the table that a type maps to. ``` csharp using Microsoft.EntityFrameworkCore; -``` -``` csharp + class MyContext : DbContext { public DbSet Blogs { get; set; } diff --git a/entity-framework/core/modeling/required-optional.md b/entity-framework/core/modeling/required-optional.md index 446642229d..14f20cfd9e 100644 --- a/entity-framework/core/modeling/required-optional.md +++ b/entity-framework/core/modeling/required-optional.md @@ -47,8 +47,8 @@ A property that would be optional by convention can be configured to be required [!code-csharp[Main](../../../samples/core/Modeling/DataAnnotations/Required.cs?highlight=14)] -# [Fluent API](#tab/fluent-api) +# [Fluent API](#tab/fluent-api) [!code-csharp[Main](../../../samples/core/Modeling/FluentAPI/Required.cs?highlight=11-13)] -*** \ No newline at end of file +*** diff --git a/entity-framework/core/modeling/table-splitting.md b/entity-framework/core/modeling/table-splitting.md index 8fdf0bd351..ec0b21e0fe 100644 --- a/entity-framework/core/modeling/table-splitting.md +++ b/entity-framework/core/modeling/table-splitting.md @@ -44,4 +44,4 @@ If any of the entity types sharing a table has a concurrency token then it must To avoid exposing it to the consuming code it's possible the create one in shadow-state. -[!code-csharp[TableSplittingConfiguration](../../../samples/core/Modeling/TableSplitting/TableSplittingContext.cs?name=ConcurrencyToken&highlight=2)] \ No newline at end of file +[!code-csharp[TableSplittingConfiguration](../../../samples/core/Modeling/TableSplitting/TableSplittingContext.cs?name=ConcurrencyToken&highlight=2)] diff --git a/entity-framework/core/modeling/value-conversions.md b/entity-framework/core/modeling/value-conversions.md index f5678211d8..b0013108e8 100644 --- a/entity-framework/core/modeling/value-conversions.md +++ b/entity-framework/core/modeling/value-conversions.md @@ -21,6 +21,7 @@ Conversions are defined using two `Func` expression trees: one from `ModelClrTyp ## Configuring a value converter Value conversions are defined on properties in the `OnModelCreating` of your `DbContext`. For example, consider an enum and entity type defined as: + ``` csharp public class Rider { @@ -36,7 +37,9 @@ public enum EquineBeast Unicorn } ``` + Then conversions can be defined in `OnModelCreating` to store the enum values as strings (for example, "Donkey", "Mule", ...) in the database: + ``` csharp protected override void OnModelCreating(ModelBuilder modelBuilder) { @@ -48,12 +51,14 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) v => (EquineBeast)Enum.Parse(typeof(EquineBeast), v)); } ``` + > [!NOTE] > A `null` value will never be passed to a value converter. This makes the implementation of conversions easier and allows them to be shared amongst nullable and non-nullable properties. ## The ValueConverter class Calling `HasConversion` as shown above will create a `ValueConverter` instance and set it on the property. The `ValueConverter` can instead be created explicitly. For example: + ``` csharp var converter = new ValueConverter( v => v.ToString(), @@ -64,6 +69,7 @@ modelBuilder .Property(e => e.Mount) .HasConversion(converter); ``` + This can be useful when multiple properties use the same conversion. > [!NOTE] @@ -72,6 +78,7 @@ This can be useful when multiple properties use the same conversion. ## Built-in converters EF Core ships with a set of pre-defined `ValueConverter` classes, found in the `Microsoft.EntityFrameworkCore.Storage.ValueConversion` namespace. These are: + * `BoolToZeroOneConverter` - Bool to zero and one * `BoolToStringConverter` - Bool to strings such as "Y" and "N" * `BoolToTwoValuesConverter` - Bool to any two values @@ -95,6 +102,7 @@ EF Core ships with a set of pre-defined `ValueConverter` classes, found in the ` * `TimeSpanToTicksConverter` - TimeSpan to ticks Notice that `EnumToStringConverter` is included in this list. This means that there is no need to specify the conversion explicitly, as shown above. Instead, just use the built-in converter: + ``` csharp var converter = new EnumToStringConverter(); @@ -103,18 +111,22 @@ modelBuilder .Property(e => e.Mount) .HasConversion(converter); ``` + Note that all the built-in converters are stateless and so a single instance can be safely shared by multiple properties. ## Pre-defined conversions For common conversions for which a built-in converter exists there is no need to specify the converter explicitly. Instead, just configure which provider type should be used and EF will automatically use the appropriate built-in converter. Enum to string conversions are used as an example above, but EF will actually do this automatically if the provider type is configured: + ``` csharp modelBuilder .Entity() .Property(e => e.Mount) .HasConversion(); ``` + The same thing can be achieved by explicitly specifying the column type. For example, if the entity type is defined like so: + ``` csharp public class Rider { @@ -124,11 +136,13 @@ public class Rider public EquineBeast Mount { get; set; } } ``` + Then the enum values will be saved as strings in the database without any further configuration in `OnModelCreating`. ## Limitations There are a few known current limitations of the value conversion system: + * As noted above, `null` cannot be converted. * There is currently no way to spread a conversion of one property to multiple columns or vice-versa. * Use of value conversions may impact the ability of EF Core to translate expressions to SQL. A warning will be logged for such cases. diff --git a/entity-framework/core/providers/cosmos/index.md b/entity-framework/core/providers/cosmos/index.md index ca2116135c..f8211811f7 100644 --- a/entity-framework/core/providers/cosmos/index.md +++ b/entity-framework/core/providers/cosmos/index.md @@ -19,13 +19,13 @@ It is strongly recommended to familiarize yourself with the [Azure Cosmos DB doc Install the [Microsoft.EntityFrameworkCore.Cosmos NuGet package](https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Cosmos/). -# [.NET Core CLI](#tab/dotnet-core-cli) +## [.NET Core CLI](#tab/dotnet-core-cli) ``` console dotnet add package Microsoft.EntityFrameworkCore.Cosmos ``` -# [Visual Studio](#tab/vs) +## [Visual Studio](#tab/vs) ``` powershell Install-Package Microsoft.EntityFrameworkCore.Cosmos diff --git a/entity-framework/core/providers/cosmos/limitations.md b/entity-framework/core/providers/cosmos/limitations.md index f4bef86097..d257fb34d1 100644 --- a/entity-framework/core/providers/cosmos/limitations.md +++ b/entity-framework/core/providers/cosmos/limitations.md @@ -29,4 +29,4 @@ The Cosmos provider has a number of limitations. Many of these limitations are a You can see the full overview of [Azure Cosmos DB supported features](https://docs.microsoft.com/en-us/azure/cosmos-db/modeling-data), these are the most notable differences compared to a relational database: - Client-initiated transactions are not supported -- Some cross-partition queries are either not supported or much slower depending on the operators involved \ No newline at end of file +- Some cross-partition queries are either not supported or much slower depending on the operators involved diff --git a/entity-framework/core/providers/cosmos/unstructured-data.md b/entity-framework/core/providers/cosmos/unstructured-data.md index 29fadebd3b..5208955ebb 100644 --- a/entity-framework/core/providers/cosmos/unstructured-data.md +++ b/entity-framework/core/providers/cosmos/unstructured-data.md @@ -57,4 +57,4 @@ In the previous example we removed the `"TrackingNumber"` property from the orde The sorted query actually returns no results. This means that one should take care to always populate properties mapped by EF Core when working with the store directly. > [!NOTE] -> This behavior might change in future versions of Cosmos. For instance, currently if the indexing policy defines the composite index {Id/? ASC, TrackingNumber/? ASC)}, then a query the has 'ORDER BY c.Id ASC, c.Discriminator ASC' __would__ return items that are missing the `"TrackingNumber"` property. \ No newline at end of file +> This behavior might change in future versions of Cosmos. For instance, currently if the indexing policy defines the composite index {Id/? ASC, TrackingNumber/? ASC)}, then a query the has 'ORDER BY c.Id ASC, c.Discriminator ASC' __would__ return items that are missing the `"TrackingNumber"` property. diff --git a/entity-framework/core/providers/in-memory/index.md b/entity-framework/core/providers/in-memory/index.md index ea00899890..1630d68661 100644 --- a/entity-framework/core/providers/in-memory/index.md +++ b/entity-framework/core/providers/in-memory/index.md @@ -13,13 +13,13 @@ This database provider allows Entity Framework Core to be used with an in-memory Install the [Microsoft.EntityFrameworkCore.InMemory NuGet package](https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.InMemory/). -# [.NET Core CLI](#tab/dotnet-core-cli) +## [.NET Core CLI](#tab/dotnet-core-cli) ``` console dotnet add package Microsoft.EntityFrameworkCore.InMemory ``` -# [Visual Studio](#tab/vs) +## [Visual Studio](#tab/vs) ``` powershell Install-Package Microsoft.EntityFrameworkCore.InMemory diff --git a/entity-framework/core/providers/index.md b/entity-framework/core/providers/index.md index 4311324a8e..efdef112db 100644 --- a/entity-framework/core/providers/index.md +++ b/entity-framework/core/providers/index.md @@ -11,6 +11,7 @@ uid: core/providers/index Entity Framework Core can access many different databases through plug-in libraries called database providers. ## Current providers + > [!IMPORTANT] > EF Core providers are built by a variety of sources. Not all providers are maintained as part of the [Entity Framework Core Project](https://github.com/aspnet/EntityFrameworkCore). When considering a provider, be sure to evaluate quality, licensing, support, etc. to ensure they meet your requirements. Also make sure you review each provider's documentation for detailed version compatibility information. @@ -43,13 +44,13 @@ Entity Framework Core can access many different databases through plug-in librar Most database providers for EF Core are distributed as NuGet packages, and can be installed as follows: -# [.NET Core CLI](#tab/dotnet-core-cli) +## [.NET Core CLI](#tab/dotnet-core-cli) ``` console dotnet add package provider_package_name ``` -# [Visual Studio](#tab/vs) +## [Visual Studio](#tab/vs) ``` powershell install-package provider_package_name diff --git a/entity-framework/core/providers/provider-log.md b/entity-framework/core/providers/provider-log.md index 56675c8905..e050e2884c 100644 --- a/entity-framework/core/providers/provider-log.md +++ b/entity-framework/core/providers/provider-log.md @@ -18,85 +18,86 @@ We are starting this log with changes from 2.1 to 2.2. Prior to 2.1 we used the Note that many of the [application-level breaking changes](../what-is-new/ef-core-3.0/breaking-changes.md) will also impact providers. -* https://github.com/aspnet/EntityFrameworkCore/pull/14022 +* * Removed obsolete APIs and collapsed optional parameter overloads * Removed DatabaseColumn.GetUnderlyingStoreType() -* https://github.com/aspnet/EntityFrameworkCore/pull/14589 +* * Removed obsolete APIs -* https://github.com/aspnet/EntityFrameworkCore/pull/15044 +* * Subclasses of CharTypeMapping may have been broken due to behavior changes required to fixing a couple bugs in the base implementation. -* https://github.com/aspnet/EntityFrameworkCore/pull/15090 +* * Added a base class for IDatabaseModelFactory and updated it to use a paramater object to mitigate future breaks. -* https://github.com/aspnet/EntityFrameworkCore/pull/15123 +* * Used parameter objects in MigrationsSqlGenerator to mitigate future breaks. -* https://github.com/aspnet/EntityFrameworkCore/pull/14972 +* * Explicit configuration of log levels required some changes to APIs that providers may be using. Specifically, if providers are using the logging infrastructure directly, then this change may break that use. Also, Providers that use the infrastructure (which will be public) going forward will need to derive from `LoggingDefinitions` or `RelationalLoggingDefinitions`. See the SQL Server and in-memory providers for examples. -* https://github.com/aspnet/EntityFrameworkCore/pull/15091 +* * Core, Relational, and Abstractions resource strings are now public. * `CoreLoggerExtensions` and `RelationalLoggerExtensions` are now public. Providers should use these APIs when logging events that are defined at the core or relational level. Do not access logging resources directly; these are still internal. * `IRawSqlCommandBuilder` has changed from a singleton service to a scoped service * `IMigrationsSqlGenerator` has changed from a singleton service to a scoped service -* https://github.com/aspnet/EntityFrameworkCore/pull/14706 +* * The infrastructure for building relational commands has been made public so it can be safely used by providers and refactored slightly. -* https://github.com/aspnet/EntityFrameworkCore/pull/14733 +* * `ILazyLoader` has changed from a scoped service to a transient service -* https://github.com/aspnet/EntityFrameworkCore/pull/14610 +* * `IUpdateSqlGenerator` has changed from a scoped service to a singleton service * Also, `ISingletonUpdateSqlGenerator` has been removed -* https://github.com/aspnet/EntityFrameworkCore/pull/15067 +* * A lot of internal code that was being used by providers has now been made public * It should no longer be necssary to reference `IndentedStringBuilder` since it has been factored out of the places that exposed it * Usages of `NonCapturingLazyInitializer` should be replaced with `LazyInitializer` from the BCL -* https://github.com/aspnet/EntityFrameworkCore/pull/14608 +* * This change is fully covered in the application breaking changes document. For providers, this may be more impacting because testing EF core can often result in hitting this issue, so test infrastructure has changed to make that less likely. -* https://github.com/aspnet/EntityFrameworkCore/issues/13961 +* * `EntityMaterializerSource` has been simplified -* https://github.com/aspnet/EntityFrameworkCore/pull/14895 +* * StartsWith translation has changed in a way that providers may want/need to react -* https://github.com/aspnet/EntityFrameworkCore/pull/15168 +* * Convention set services have changed. Providers should now inherit from either "ProviderConventionSet" or "RelationalConventionSet". * Customizations can be added through `IConventionSetCustomizer` services, but this is intended to be used by other extensions, not providers. * Conventions used at runtime should be resolved from `IConventionSetBuilder`. -* https://github.com/aspnet/EntityFrameworkCore/pull/15288 - Data seeding has been refactored into a public API to avoid the need to use internal types. This should only impact non-relational providers, since seeding is handled by the base relational class for all relational providers. +* + * Data seeding has been refactored into a public API to avoid the need to use internal types. This should only impact non-relational providers, since seeding is handled by the base relational class for all relational providers. ## 2.1 ---> 2.2 ### Test-only changes -* https://github.com/aspnet/EntityFrameworkCore/pull/12057 - Allow customizable SQL delimeters in tests +* - Allow customizable SQL delimeters in tests * Test changes that allow non-strict floating point comparisons in BuiltInDataTypesTestBase * Test changes that allow query tests to be re-used with different SQL delimeters -* https://github.com/aspnet/EntityFrameworkCore/pull/12072 - Add DbFunction tests to the relational specification tests +* - Add DbFunction tests to the relational specification tests * Such that these tests can be run against all database providers -* https://github.com/aspnet/EntityFrameworkCore/pull/12362 - Async test cleanup +* - Async test cleanup * Remove `Wait` calls, unneeded async, and renamed some test methods -* https://github.com/aspnet/EntityFrameworkCore/pull/12666 - Unify logging test infrastructure +* - Unify logging test infrastructure * Added `CreateListLoggerFactory` and removed some previous logging infrastructure, which will require providers using these tests to react -* https://github.com/aspnet/EntityFrameworkCore/pull/12500 - Run more query tests both synchronously and asynchronously +* - Run more query tests both synchronously and asynchronously * Test names and factoring has changed, which will require providers using these tests to react -* https://github.com/aspnet/EntityFrameworkCore/pull/12766 - Renaming navigations in the ComplexNavigations model +* - Renaming navigations in the ComplexNavigations model * Providers using these tests may need to react -* https://github.com/aspnet/EntityFrameworkCore/pull/12141 - Return the context to the pool instead of disposing in functional tests +* - Return the context to the pool instead of disposing in functional tests * This change includes some test refactoring which may require providers to react ### Test and product code changes -* https://github.com/aspnet/EntityFrameworkCore/pull/12109 - Consolidate RelationalTypeMapping.Clone methods +* - Consolidate RelationalTypeMapping.Clone methods * Changes in 2.1 to the RelationalTypeMapping allowed for a simplification in derived classes. We don't believe this was breaking to providers, but providers can take advantage of this change in their derived type mapping classes. -* https://github.com/aspnet/EntityFrameworkCore/pull/12069 - Tagged or named queries +* - Tagged or named queries * Adds infrastructure for tagging LINQ queries and having those tags show up as comments in the SQL. This may require providers to react in SQL generation. -* https://github.com/aspnet/EntityFrameworkCore/pull/13115 - Support spatial data via NTS +* - Support spatial data via NTS * Allows type mappings and member translators to be registered outside of the provider * Providers must call base.FindMapping() in their ITypeMappingSource implementation for it to work * Follow this pattern to add spatial support to your provider that is consistent across providers. -* https://github.com/aspnet/EntityFrameworkCore/pull/13199 - Add enhanced debugging for service provider creation +* - Add enhanced debugging for service provider creation * Allows DbContextOptionsExtensions to implement a new interface that can help people understand why the internal service provider is being re-built -* https://github.com/aspnet/EntityFrameworkCore/pull/13289 - Adds CanConnect API for use by health checks +* - Adds CanConnect API for use by health checks * This PR adds the concept of `CanConnect` which will be used by ASP.NET Core health checks to determine if the database is available. By default, the relational implementation just calls `Exist`, but providers can implement something different if necessary. Non-relational providers will need to implement the new API in order for the health check to be usable. -* https://github.com/aspnet/EntityFrameworkCore/pull/13306 - Update base RelationalTypeMapping to not set DbParameter Size +* - Update base RelationalTypeMapping to not set DbParameter Size * Stop setting Size by default since it can cause truncation. Providers may need to add their own logic if Size needs to be set. -* https://github.com/aspnet/EntityFrameworkCore/pull/13372 - RevEng: Always specify column type for decimal columns +* - RevEng: Always specify column type for decimal columns * Always configure column type for decimal columns in scaffolded code rather than configuring by convention. * Providers should not require any changes on their end. -* https://github.com/aspnet/EntityFrameworkCore/pull/13469 - Adds CaseExpression for generating SQL CASE expressions -* https://github.com/aspnet/EntityFrameworkCore/pull/13648 - Adds the ability to specify type mappings on SqlFunctionExpression to improve store type inference of arguments and results. +* - Adds CaseExpression for generating SQL CASE expressions +* - Adds the ability to specify type mappings on SqlFunctionExpression to improve store type inference of arguments and results. diff --git a/entity-framework/core/providers/sql-server/index.md b/entity-framework/core/providers/sql-server/index.md index ab1e6276ad..e3ff4493cd 100644 --- a/entity-framework/core/providers/sql-server/index.md +++ b/entity-framework/core/providers/sql-server/index.md @@ -13,13 +13,13 @@ This database provider allows Entity Framework Core to be used with Microsoft SQ Install the [Microsoft.EntityFrameworkCore.SqlServer NuGet package](https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.SqlServer/). -# [.NET Core CLI](#tab/dotnet-core-cli) +## [.NET Core CLI](#tab/dotnet-core-cli) ``` console dotnet add package Microsoft.EntityFrameworkCore.SqlServer ``` -# [Visual Studio](#tab/vs) +## [Visual Studio](#tab/vs) ``` powershell Install-Package Microsoft.EntityFrameworkCore.SqlServer diff --git a/entity-framework/core/providers/sqlite/index.md b/entity-framework/core/providers/sqlite/index.md index 0ea1b3bde4..27cec8c2e2 100644 --- a/entity-framework/core/providers/sqlite/index.md +++ b/entity-framework/core/providers/sqlite/index.md @@ -13,13 +13,13 @@ This database provider allows Entity Framework Core to be used with SQLite. The Install the [Microsoft.EntityFrameworkCore.Sqlite NuGet package](https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Sqlite/). -# [.NET Core CLI](#tab/dotnet-core-cli) +## [.NET Core CLI](#tab/dotnet-core-cli) ``` console dotnet add package Microsoft.EntityFrameworkCore.Sqlite ``` -# [Visual Studio](#tab/vs) +## [Visual Studio](#tab/vs) ``` powershell Install-Package Microsoft.EntityFrameworkCore.Sqlite diff --git a/entity-framework/core/providers/writing-a-provider.md b/entity-framework/core/providers/writing-a-provider.md index 6d9f81966d..668bd5029d 100644 --- a/entity-framework/core/providers/writing-a-provider.md +++ b/entity-framework/core/providers/writing-a-provider.md @@ -13,7 +13,7 @@ For information about writing an Entity Framework Core database provider, see [S > [!NOTE] > These posts have not been updated since EF Core 1.1 and there have been significant changes since that time [Issue 681](https://github.com/aspnet/EntityFramework.Docs/issues/681) is tracking updates to this documentation. -The EF Core codebase is open source and contains several database providers that can be used as a reference. You can find the source code at https://github.com/aspnet/EntityFrameworkCore. It may also be helpful to look at the code for commonly used third-party providers, such as [Npgsql](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL), [Pomelo MySQL](https://github.com/PomeloFoundation/Pomelo.EntityFrameworkCore.MySql), and [SQL Server Compact](https://github.com/ErikEJ/EntityFramework.SqlServerCompact). In particular, these projects are setup to extend from and run functional tests that we publish on NuGet. This kind of setup is strongly recommended. +The EF Core codebase is open source and contains several database providers that can be used as a reference. You can find the source code at . It may also be helpful to look at the code for commonly used third-party providers, such as [Npgsql](https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL), [Pomelo MySQL](https://github.com/PomeloFoundation/Pomelo.EntityFrameworkCore.MySql), and [SQL Server Compact](https://github.com/ErikEJ/EntityFramework.SqlServerCompact). In particular, these projects are setup to extend from and run functional tests that we publish on NuGet. This kind of setup is strongly recommended. ## Keeping up-to-date with provider changes @@ -28,6 +28,7 @@ We suggest using the following naming for NuGet packages. This is consistent wit `.EntityFrameworkCore.` For example: + * `Microsoft.EntityFrameworkCore.SqlServer` * `Npgsql.EntityFrameworkCore.PostgreSQL` * `EntityFrameworkCore.SqlServerCompact40` diff --git a/entity-framework/core/querying/how-query-works.md b/entity-framework/core/querying/how-query-works.md index 1416faff86..cde8f3e519 100644 --- a/entity-framework/core/querying/how-query-works.md +++ b/entity-framework/core/querying/how-query-works.md @@ -35,6 +35,7 @@ The following is a high level overview of the process each query goes through. When you call LINQ operators, you are simply building up an in-memory representation of the query. The query is only sent to the database when the results are consumed. The most common operations that result in the query being sent to the database are: + * Iterating the results in a `for` loop * Using an operator such as `ToList`, `ToArray`, `Single`, `Count` * Databinding the results of a query to a UI diff --git a/entity-framework/core/querying/related-data.md b/entity-framework/core/querying/related-data.md index c46aea7e98..e54f8f76f8 100644 --- a/entity-framework/core/querying/related-data.md +++ b/entity-framework/core/querying/related-data.md @@ -9,6 +9,7 @@ uid: core/querying/related-data # Loading Related Data Entity Framework Core allows you to use the navigation properties in your model to load related entities. There are three common O/RM patterns used to load related data. + * **Eager loading** means that the related data is loaded from the database as part of the initial query. * **Explicit loading** means that the related data is explicitly loaded from the database at a later time. * **Lazy loading** means that the related data is transparently loaded from the database when the navigation property is accessed. @@ -52,7 +53,7 @@ You may want to include multiple related entities for one of the entities that i ### Include on derived types -You can include related data from navigations defined only on a derived type using `Include` and `ThenInclude`. +You can include related data from navigations defined only on a derived type using `Include` and `ThenInclude`. Given the following model: @@ -90,17 +91,20 @@ public class School Contents of `School` navigation of all People who are Students can be eagerly loaded using a number of patterns: -- using cast +* using cast + ```csharp context.People.Include(person => ((Student)person).School).ToList() ``` -- using `as` operator +* using `as` operator + ```csharp context.People.Include(person => (person as Student).School).ToList() ``` -- using overload of `Include` that takes parameter of type `string` +* using overload of `Include` that takes parameter of type `string` + ```csharp context.People.Include("School").ToList() ``` @@ -135,6 +139,7 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) .UseLazyLoadingProxies() .UseSqlServer(myConnectionString); ``` + Or when using AddDbContext: ```csharp diff --git a/entity-framework/core/querying/tags.md b/entity-framework/core/querying/tags.md index 3510fac31b..f82d89a644 100644 --- a/entity-framework/core/querying/tags.md +++ b/entity-framework/core/querying/tags.md @@ -7,11 +7,12 @@ uid: core/querying/tags --- # Query tags + > [!NOTE] > This feature is new in EF Core 2.2. This feature helps correlate LINQ queries in code with generated SQL queries captured in logs. -You annotate a LINQ query using the new `TagWith()` method: +You annotate a LINQ query using the new `TagWith()` method: ``` csharp var nearestFriends = @@ -44,7 +45,7 @@ IQueryable Limit(IQueryable source, int limit) => source.TagWith("Limit").Take(limit); ``` -The following query: +The following query: ``` csharp var results = Limit(GetNearestFriends(myLocation), 25).ToList(); @@ -87,6 +88,7 @@ ORDER BY [f].[Location].STDistance(@__myLocation_0) DESC ``` ## Known limitations + **Query tags aren't parameterizable:** EF Core always treats query tags in the LINQ query as string literals that are included in the generated SQL. -Compiled queries that take query tags as parameters aren't allowed. \ No newline at end of file +Compiled queries that take query tags as parameters aren't allowed. diff --git a/entity-framework/core/saving/cascade-delete.md b/entity-framework/core/saving/cascade-delete.md index 8d94cf4119..f95125717e 100644 --- a/entity-framework/core/saving/cascade-delete.md +++ b/entity-framework/core/saving/cascade-delete.md @@ -12,9 +12,11 @@ Cascade delete is commonly used in database terminology to describe a characteri EF Core implements several different delete behaviors and allows for the configuration of the delete behaviors of individual relationships. EF Core also implements conventions that automatically configure useful default delete behaviors for each relationship based on the [requiredness of the relationship](../modeling/relationships.md#required-and-optional-relationships). ## Delete behaviors + Delete behaviors are defined in the *DeleteBehavior* enumerator type and can be passed to the *OnDelete* fluent API to control whether the deletion of a principal/parent entity or the severing of the relationship to dependent/child entities should have a side effect on the dependent/child entities. There are three actions EF can take when a principal/parent entity is deleted or the relationship to the child is severed: + * The child/dependent can be deleted * The child's foreign key values can be set to null * The child remains unchanged @@ -27,6 +29,7 @@ For the second action above, setting a foreign key value to null is not valid if There are four delete behaviors, as listed in the tables below. ### Optional relationships + For optional relationships (nullable foreign key) it _is_ possible to save a null foreign key value, which results in the following effects: | Behavior Name | Effect on dependent/child in memory | Effect on dependent/child in database | @@ -37,6 +40,7 @@ For optional relationships (nullable foreign key) it _is_ possible to save a nul | **Restrict** | None | None | ### Required relationships + For required relationships (non-nullable foreign key) it is _not_ possible to save a null foreign key value, which results in the following effects: | Behavior Name | Effect on dependent/child in memory | Effect on dependent/child in database | @@ -49,6 +53,7 @@ For required relationships (non-nullable foreign key) it is _not_ possible to sa In the tables above, *None* can result in a constraint violation. For example, if a principal/child entity is deleted but no action is taken to change the foreign key of a dependent/child, then the database will likely throw on SaveChanges due to a foreign constraint violation. At a high level: + * If you have entities that cannot exist without a parent, and you want EF to take care for deleting the children automatically, then use *Cascade*. * Entities that cannot exist without a parent usually make use of required relationships, for which *Cascade* is the default. * If you have entities that may or may not have a parent, and you want EF to take care of nulling out the foreign key for you, then use *ClientSetNull* @@ -101,7 +106,7 @@ Let's walk through each variation to understand what is happening. ### DeleteBehavior.ClientSetNull or DeleteBehavior.SetNull with required relationship -```console +``` output After loading entities: Blog '1' is in state Unchanged with 2 posts referenced. Post '1' is in state Unchanged with FK '1' and reference to blog '1'. @@ -124,7 +129,7 @@ Let's walk through each variation to understand what is happening. ### DeleteBehavior.ClientSetNull or DeleteBehavior.SetNull with optional relationship -```console +``` output After loading entities: Blog '1' is in state Unchanged with 2 posts referenced. Post '1' is in state Unchanged with FK '1' and reference to blog '1'. @@ -154,7 +159,7 @@ Let's walk through each variation to understand what is happening. ### DeleteBehavior.Restrict with required or optional relationship -```console +``` output After loading entities: Blog '1' is in state Unchanged with 2 posts referenced. Post '1' is in state Unchanged with FK '1' and reference to blog '1'. @@ -183,7 +188,7 @@ Let's walk through each variation to understand what is happening. ### DeleteBehavior.Cascade with required or optional relationship -```console +``` output After loading entities: Blog '1' is in state Unchanged with 2 posts referenced. Post '1' is in state Unchanged with FK '1' and reference to blog '1'. @@ -211,7 +216,7 @@ Let's walk through each variation to understand what is happening. ### DeleteBehavior.ClientSetNull or DeleteBehavior.SetNull with required relationship -```console +``` output After loading entities: Blog '1' is in state Unchanged with 2 posts referenced. Post '1' is in state Unchanged with FK '1' and reference to blog '1'. @@ -234,7 +239,7 @@ Let's walk through each variation to understand what is happening. ### DeleteBehavior.ClientSetNull or DeleteBehavior.SetNull with optional relationship -```console +``` output After loading entities: Blog '1' is in state Unchanged with 2 posts referenced. Post '1' is in state Unchanged with FK '1' and reference to blog '1'. @@ -262,7 +267,7 @@ Let's walk through each variation to understand what is happening. ### DeleteBehavior.Restrict with required or optional relationship -```console +``` output After loading entities: Blog '1' is in state Unchanged with 2 posts referenced. Post '1' is in state Unchanged with FK '1' and reference to blog '1'. diff --git a/entity-framework/core/saving/concurrency.md b/entity-framework/core/saving/concurrency.md index fdd60a5fcd..4c3091b2a7 100644 --- a/entity-framework/core/saving/concurrency.md +++ b/entity-framework/core/saving/concurrency.md @@ -50,11 +50,9 @@ Resolving a concurrency conflict involves merging the pending changes from the c **There are three sets of values available to help resolve a concurrency conflict:** -* **Current values** are the values that the application was attempting to write to the database. - -* **Original values** are the values that were originally retrieved from the database, before any edits were made. - -* **Database values** are the values currently stored in the database. +- **Current values** are the values that the application was attempting to write to the database. +- **Original values** are the values that were originally retrieved from the database, before any edits were made. +- **Database values** are the values currently stored in the database. The general approach to handle a concurrency conflicts is: diff --git a/entity-framework/core/saving/disconnected-entities.md b/entity-framework/core/saving/disconnected-entities.md index 539405355e..c4f71b9cc9 100644 --- a/entity-framework/core/saving/disconnected-entities.md +++ b/entity-framework/core/saving/disconnected-entities.md @@ -12,11 +12,13 @@ A DbContext instance will automatically track entities returned from the databas However, sometimes entities are queried using one context instance and then saved using a different instance. This often happens in "disconnected" scenarios such as a web application where the entities are queried, sent to the client, modified, sent back to the server in a request, and then saved. In this case, the second context instance needs to know whether the entities are new (should be inserted) or existing (should be updated). -> [!TIP] + +> [!TIP] > You can view this article's [sample](https://github.com/aspnet/EntityFramework.Docs/tree/master/samples/core/Saving/Disconnected/) on GitHub. > [!TIP] > EF Core can only track one instance of any entity with a given primary key value. The best way to avoid this being an issue is to use a short-lived context for each unit-of-work such that the context starts empty, has entities attached to it, saves those entities, and then the context is disposed and discarded. + ## Identifying new entities @@ -44,8 +46,9 @@ However, EF also has a built-in way to do this for any entity type and key type: ### With other keys Some other mechanism is needed to identify new entities when key values are not generated automatically. There are two general approaches to this: - * Query for the entity - * Pass a flag from the client + +* Query for the entity +* Pass a flag from the client To query for the entity, just use the Find method: @@ -73,6 +76,7 @@ If the entity is not using auto-generated keys, then the application must decide [!code-csharp[Main](../../../samples/core/Saving/Disconnected/Sample.cs#InsertOrUpdateSingleEntityWithFind)] The steps here are: + * If Find returns null, then the database doesn't already contain the blog with this ID, so we call Add mark it for insertion. * If Find returns an entity, then it exists in the database and the context is now tracking the existing entity * We then use SetValues to set the values for all properties on this entity to those that came from the client. diff --git a/entity-framework/core/saving/explicit-values-generated-properties.md b/entity-framework/core/saving/explicit-values-generated-properties.md index 33fb6b3a33..56847354ad 100644 --- a/entity-framework/core/saving/explicit-values-generated-properties.md +++ b/entity-framework/core/saving/explicit-values-generated-properties.md @@ -28,6 +28,7 @@ The `Employee.EmploymentStarted` property is configured to have values generated [!code-csharp[Main](../../../samples/core/Saving/ExplicitValuesGenerateProperties/EmployeeContext.cs#EmploymentStarted)] The following code inserts two employees into the database. + * For the first, no value is assigned to `Employee.EmploymentStarted` property, so it remains set to the CLR default value for `DateTime`. * For the second, we have set an explicit value of `1-Jan-2000`. @@ -75,6 +76,7 @@ There is also a trigger in the database to generate values for the `LastPayRaise [!code-sql[Main](../../../samples/core/Saving/ExplicitValuesGenerateProperties/employee_UPDATE.sql)] The following code increases the salary of two employees in the database. + * For the first, no value is assigned to `Employee.LastPayRaise` property, so it remains set to null. * For the second, we have set an explicit value of one week ago (back dating the pay raise). diff --git a/entity-framework/core/saving/transactions.md b/entity-framework/core/saving/transactions.md index 77a987a438..192d7a459a 100644 --- a/entity-framework/core/saving/transactions.md +++ b/entity-framework/core/saving/transactions.md @@ -93,9 +93,9 @@ It is also possible to enlist in an explicit transaction. ### Limitations of System.Transactions -1. EF Core relies on database providers to implement support for System.Transactions. Although support is quite common among ADO.NET providers for .NET Framework, the API has only been recently added to .NET Core and hence support is not as widespread. If a provider does not implement support for System.Transactions, it is possible that calls to these APIs will be completely ignored. SqlClient for .NET Core does support it from 2.1 onwards. SqlClient for .NET Core 2.0 will throw an exception if you attempt to use the feature. +1. EF Core relies on database providers to implement support for System.Transactions. Although support is quite common among ADO.NET providers for .NET Framework, the API has only been recently added to .NET Core and hence support is not as widespread. If a provider does not implement support for System.Transactions, it is possible that calls to these APIs will be completely ignored. SqlClient for .NET Core does support it from 2.1 onwards. SqlClient for .NET Core 2.0 will throw an exception if you attempt to use the feature. > [!IMPORTANT] - > It is recommended that you test that the API behaves correctly with your provider before you rely on it for managing transactions. You are encouraged to contact the maintainer of the database provider if it does not. + > It is recommended that you test that the API behaves correctly with your provider before you rely on it for managing transactions. You are encouraged to contact the maintainer of the database provider if it does not. -2. As of version 2.1, the System.Transactions implementation in .NET Core does not include support for distributed transactions, therefore you cannot use `TransactionScope` or `CommittableTransaction` to coordinate transactions across multiple resource managers. +2. As of version 2.1, the System.Transactions implementation in .NET Core does not include support for distributed transactions, therefore you cannot use `TransactionScope` or `CommittableTransaction` to coordinate transactions across multiple resource managers. diff --git a/entity-framework/core/what-is-new/ef-core-1.0.md b/entity-framework/core/what-is-new/ef-core-1.0.md index ccd1609ec2..0bb93efcc8 100644 --- a/entity-framework/core/what-is-new/ef-core-1.0.md +++ b/entity-framework/core/what-is-new/ef-core-1.0.md @@ -8,91 +8,167 @@ uid: core/what-is-new/ef-core-1.0 # Features included in EF Core 1.0 ## Platforms + ### .NET Framework 4.5.1 + Includes Console, WPF, WinForms, ASP.NET 4, etc. + ### .NET Standard 1.3 + Including ASP.NET Core targeting both .NET Framework and .NET Core on Windows, OSX, and Linux. ## Modelling + ### Basic modelling + Based on POCO entities with get/set properties of common scalar types (`int`, `string`, etc.). + ### Relationships and navigation properties + One-to-many and One-to-zero-or-one relationships can be specified in the model based on a foreign key. Navigation properties of simple collection or reference types can be associated with these relationships. + ### Built-in conventions + These build an initial model based on the shape of the entity classes. + ### Fluent API + Allows you to override the `OnModelCreating` method on your context to further configure the model that was discovered by convention. + ### Data annotations + Are attributes that can be added to your entity classes/properties and will influence the EF model. For example, adding `[Required]` will let EF know that a property is required. + ### Relational Table mapping + Allows entities to be mapped to tables/columns. + ### Key value generation + Including client-side generation and database generation. + ### Database generated values + Allows for values to be generated by the database on insert (default values) or update (computed columns). + ### Sequences in SQL Server + Allows for sequence objects to be defined in the model. + ### Unique constraints + Allows for the definition of alternate keys and the ability to define relationships that target that key. + ### Indexes + Defining indexes in the model automatically introduces indexes in the database. Unique indexes are also supported. + ### Shadow state properties + Allows for properties to be defined in the model that are not declared and are not stored in the .NET class but can be tracked and updated by EF Core. Commonly used for foreign key properties when exposing these in the object is not desired. + ### Table-Per-Hierarchy inheritance pattern + Allows entities in an inheritance hierarchy to be saved to a single table using a discriminator column to identify they entity type for a given record in the database. + ### Model validation + Detects invalid patterns in the model and provides helpful error messages. ## Change tracking + ### Snapshot change tracking + Allows changes in entities to be detected automatically by comparing current state against a copy (snapshot) of the original state. + ### Notification change tracking + Allows your entities to notify the change tracker when property values are modified. + ### Accessing tracked state + Via `DbContext.Entry` and `DbContext.ChangeTracker`. + ### Attaching detached entities/graphs + The new `DbContext.AttachGraph` API helps re-attach entities to a context in order to save new/modified entities. ## Saving data + ### Basic save functionality + Allows changes to entity instances to be persisted to the database. + ### Optimistic Concurrency + Protects against overwriting changes made by another user since data was fetched from the database. + ### Async SaveChanges + Can free up the current thread to process other requests while the database processes the commands issued from `SaveChanges`. + ### Database Transactions + Means that `SaveChanges` is always atomic (meaning it either completely succeeds, or no changes are made to the database). There are also transaction related APIs to allow sharing transactions between context instances etc. + ### Relational: Batching of statements + Provides better performance by batching up multiple INSERT/UPDATE/DELETE commands into a single roundtrip to the database. ## Query + ### Basic LINQ support + Provides the ability to use LINQ to retrieve data from the database. + ### Mixed client/server evaluation + Enables queries to contain logic that cannot be evaluated in the database, and must therefore be evaluated after the data is retrieved into memory. + ### NoTracking + Queries enables quicker query execution when the context does not need to monitor for changes to the entity instances (this is useful if the results are read-only). + ### Eager loading + Provides the `Include` and `ThenInclude` methods to identify related data that should also be fetched when querying. + ### Async query + Can free up the current thread (and it's associated resources) to process other requests while the database processes the query. + ### Raw SQL queries + Provides the `DbSet.FromSql` method to use raw SQL queries to fetch data. These queries can also be composed on using LINQ. -## Database schema management +## Database schema management + ### Database creation/deletion APIs + Are mostly designed for testing where you want to quickly create/delete the database without using migrations. + ### Relational database migrations + Allow a relational database schema to evolve overtime as your model changes. + ### Reverse engineer from database + Scaffolds an EF model based on an existing relational database schema. ## Database providers + ### SQL Server + Connects to Microsoft SQL Server 2008 onwards. + ### SQLite + Connects to a SQLite 3 database. + ### In-Memory + Is designed to easily enable testing without connecting to a real database. + ### 3rd party providers + Several providers are available for other database engines. See [Database Providers](../providers/index.md) for a complete list. diff --git a/entity-framework/core/what-is-new/ef-core-1.1.md b/entity-framework/core/what-is-new/ef-core-1.1.md index 82aea3ff65..21bc27ba93 100644 --- a/entity-framework/core/what-is-new/ef-core-1.1.md +++ b/entity-framework/core/what-is-new/ef-core-1.1.md @@ -7,24 +7,38 @@ uid: core/what-is-new/ef-core-1.1 --- # New features in EF Core 1.1 -## Modelling +## Modeling + ### Field mapping + Allows you to configure a backing field for a property. This can be useful for read-only properties, or data that has Get/Set methods rather than a property. + ### Mapping to Memory-Optimized Tables in SQL Server + You can specify that the table an entity is mapped to is memory-optimized. When using EF Core to create and maintain a database based on your model (either with migrations or `Database.EnsureCreated()`), a memory-optimized table will be created for these entities. ## Change tracking + ### Additional change tracking APIs from EF6 + Such as `Reload`, `GetModifiedProperties`, `GetDatabaseValues` etc. ## Query + ### Explicit Loading + Allows you to trigger population of a navigation property on an entity that was previously loaded from the database. + ### DbSet.Find + Provides an easy way to fetch an entity based on its primary key value. ## Other + ### Connection resiliency + Automatically retries failed database commands. This is especially useful when connection to SQL Azure, where transient failures are common. + ### Simplified service replacement + Makes it easier to replace internal services that EF uses. diff --git a/entity-framework/core/what-is-new/ef-core-2.0.md b/entity-framework/core/what-is-new/ef-core-2.0.md index 3268b0b6a7..a1d0b70698 100644 --- a/entity-framework/core/what-is-new/ef-core-2.0.md +++ b/entity-framework/core/what-is-new/ef-core-2.0.md @@ -9,6 +9,7 @@ uid: core/what-is-new/ef-core-2.0 # New features in EF Core 2.0 ## .NET Standard 2.0 + EF Core now targets .NET Standard 2.0, which means it can work with .NET Core 2.0, .NET Framework 4.6.1, and other libraries that implement .NET Standard 2.0. See [Supported .NET Implementations](../platforms/index.md) for more details on what is supported. @@ -27,6 +28,7 @@ modelBuilder.Entity() modelBuilder.Entity().ToTable("Products"); modelBuilder.Entity().ToTable("Products"); ``` + Read the [section on table splitting](xref:core/modeling/table-splitting) for more information on this feature. ### Owned types @@ -60,6 +62,7 @@ public class StreetAddress public string City { get; set; } } ``` + Read the [section on owned entity types](xref:core/modeling/owned-entities) for more information on this feature. ### Model-level query filters @@ -87,6 +90,7 @@ public class BloggingContext : DbContext } } ``` + We define a model-level filter that implements multi-tenancy and soft-delete for instances of the `Post` Entity Type. Note the use of a DbContext instance level property: `TenantId`. Model-level filters will use the value from the correct context instance (that is, the context instance that is executing the query). Filters may be disabled for individual LINQ queries using the IgnoreQueryFilters() operator. @@ -293,9 +297,11 @@ public class MyPluralizer : IPluralizer ## Others ### Move ADO.NET SQLite provider to SQLitePCL.raw + This gives us a more robust solution in Microsoft.Data.Sqlite for distributing native SQLite binaries on different platforms. ### Only one provider per model + Significantly augments how providers can interact with the model and simplifies how conventions, annotations and fluent APIs work with different providers. EF Core 2.0 will now build a different [IModel](https://github.com/aspnet/EntityFramework/blob/master/src/EFCore/Metadata/IModel.cs) for each different provider being used. This is usually transparent to the application. This has facilitated a simplification of lower-level metadata APIs such that any access to *common relational metadata concepts* is always made through a call to `.Relational` instead of `.SqlServer`, `.Sqlite`, etc. diff --git a/entity-framework/core/what-is-new/ef-core-2.1.md b/entity-framework/core/what-is-new/ef-core-2.1.md index 4a732fbe21..8fb3d7c76f 100644 --- a/entity-framework/core/what-is-new/ef-core-2.1.md +++ b/entity-framework/core/what-is-new/ef-core-2.1.md @@ -11,16 +11,19 @@ uid: core/what-is-new/ef-core-2.1 Besides numerous bug fixes and small functional and performance enhancements, EF Core 2.1 includes some compelling new features: ## Lazy loading + EF Core now contains the necessary building blocks for anyone to author entity classes that can load their navigation properties on demand. We have also created a new package, Microsoft.EntityFrameworkCore.Proxies, that leverages those building blocks to produce lazy loading proxy classes based on minimally modified entity classes (for example, classes with virtual navigation properties). Read the [section on lazy loading](xref:core/querying/related-data#lazy-loading) for more information about this topic. ## Parameters in entity constructors + As one of the required building blocks for lazy loading, we enabled the creation of entities that take parameters in their constructors. You can use parameters to inject property values, lazy loading delegates, and services. Read the [section on entity constructor with parameters](xref:core/modeling/constructors) for more information about this topic. ## Value conversions + Until now, EF Core could only map properties of types natively supported by the underlying database provider. Values were copied back and forth between columns and properties without any transformation. Starting with EF Core 2.1, value conversions can be applied to transform the values obtained from columns before they are applied to properties, and vice versa. We have a number of conversions that can be applied by convention as necessary, as well as an explicit configuration API that allows registering custom conversions between columns and properties. Some of the application of this feature are: - Storing enums as strings @@ -30,6 +33,7 @@ Until now, EF Core could only map properties of types natively supported by the Read the [section on value conversions](xref:core/modeling/value-conversions) for more information about this topic. ## LINQ GroupBy translation + Before version 2.1, in EF Core the GroupBy LINQ operator would always be evaluated in memory. We now support translating it to the SQL GROUP BY clause in most common cases. This example shows a query with GroupBy used to compute various aggregate functions: @@ -58,6 +62,7 @@ GROUP BY [o].[CustomerId], [o].[EmployeeId]; ``` ## Data Seeding + With the new release it will be possible to provide initial data to populate a database. Unlike in EF6, seeding data is associated to an entity type as part of the model configuration. Then EF Core migrations can automatically compute what insert, update or delete operations need to be applied when upgrading the database to a new version of the model. As an example, you can use this to configure seed data for a Post in `OnModelCreating`: @@ -69,6 +74,7 @@ modelBuilder.Entity().HasData(new Post{ Id = 1, Text = "Hello World!" }); Read the [section on data seeding](xref:core/modeling/data-seeding) for more information about this topic. ## Query types + An EF Core model can now include query types. Unlike entity types, query types do not have keys defined on them and cannot be inserted, deleted or updated (that is, they are read-only), but they can be returned directly by queries. Some of the usage scenarios for query types are: - Mapping to views without primary keys @@ -79,6 +85,7 @@ An EF Core model can now include query types. Unlike entity types, query types d Read the [section on query types](xref:core/modeling/keyless-entity-types) for more information about this topic. ## Include for derived types + It will be now possible to specify navigation properties only defined on derived types when writing expressions for the `Include` method. For the strongly typed version of `Include`, we support using either an explicit cast or the `as` operator. We also now support referencing the names of navigation property defined on derived types in the string version of `Include`: ``` csharp @@ -90,14 +97,17 @@ var option3 = context.People.Include("School"); Read the [section on Include with derived types](xref:core/querying/related-data#include-on-derived-types) for more information about this topic. ## System.Transactions support + We have added the ability to work with System.Transactions features such as TransactionScope. This will work on both .NET Framework and .NET Core when using database providers that support it. Read the [section on System.Transactions](xref:core/saving/transactions#using-systemtransactions) for more information about this topic. ## Better column ordering in initial migration + Based on customer feedback, we have updated migrations to initially generate columns for tables in the same order as properties are declared in classes. Note that EF Core cannot change order when new members are added after the initial table creation. ## Optimization of correlated subqueries + We have improved our query translation to avoid executing "N + 1" SQL queries in many common scenarios in which the usage of a navigation property in the projection leads to joining data from the root query with data from a correlated subquery. The optimization requires buffering the results from the subquery, and we require that you modify the query to opt-in the new behavior. As an example, the following query normally gets translated into one query for Customers, plus N (where "N" is the number of customers returned) separate queries for Orders: @@ -142,6 +152,7 @@ The _dotnet-ef_ commands are now part of the .NET Core SDK, therefore it will no See the section on [installing the tools](xref:core/miscellaneous/cli/dotnet#installing-the-tools) for more details on how to enable command line tools for different versions of the .NET Core SDK and EF Core. ## Microsoft.EntityFrameworkCore.Abstractions package + The new package contains attributes and interfaces that you can use in your projects to light up EF Core features without taking a dependency on EF Core as a whole. For example, the [Owned] attribute and the ILazyLoader interface are located here. ## State change events diff --git a/entity-framework/core/what-is-new/ef-core-2.2.md b/entity-framework/core/what-is-new/ef-core-2.2.md index edd7aae59e..ae6cbbb3ea 100644 --- a/entity-framework/core/what-is-new/ef-core-2.2.md +++ b/entity-framework/core/what-is-new/ef-core-2.2.md @@ -11,7 +11,7 @@ uid: core/what-is-new/ef-core-2.2 ## Spatial data support Spatial data can be used to represent the physical location and shape of objects. -Many databases can natively store, index, and query spatial data. +Many databases can natively store, index, and query spatial data. Common scenarios include querying for objects within a given distance, and testing if a polygon contains a given location. EF Core 2.2 now supports working with spatial data from various databases using types from the [NetTopologySuite](https://github.com/NetTopologySuite/NetTopologySuite) (NTS) library. @@ -36,7 +36,7 @@ namespace MyApp public Point Location { get; set; } } } -``` +``` You can then persist entities with spatial data: @@ -52,6 +52,7 @@ using (var context = new MyDbContext()) context.SaveChanges(); } ``` + And you can execute database queries based on spatial data and operations: ``` csharp @@ -61,7 +62,7 @@ And you can execute database queries based on spatial data and operations: select f).Take(5).ToList(); ``` -For more information on this feature, see the [spatial types documentation](xref:core/modeling/spatial). +For more information on this feature, see the [spatial types documentation](xref:core/modeling/spatial). ## Collections of owned entities @@ -70,7 +71,8 @@ EF Core 2.2 extends the ability to express ownership to one-to-many associations Ownership helps constrain how entities are used. For example, owned entities: -- Can only ever appear on navigation properties of other entity types. + +- Can only ever appear on navigation properties of other entity types. - Are automatically loaded, and can only be tracked by a DbContext alongside their owner. In relational databases, owned collections are mapped to separate tables from the owner, just like regular one-to-many associations. @@ -108,4 +110,4 @@ FROM [Friends] AS [f] ORDER BY [f].[Location].STDistance(@__myLocation_0) DESC ``` -For more information, see the [query tags documentation](xref:core/querying/tags). \ No newline at end of file +For more information, see the [query tags documentation](xref:core/querying/tags). diff --git a/entity-framework/core/what-is-new/ef-core-3.0/breaking-changes.md b/entity-framework/core/what-is-new/ef-core-3.0/breaking-changes.md index e25afbff7a..ad238a2181 100644 --- a/entity-framework/core/what-is-new/ef-core-3.0/breaking-changes.md +++ b/entity-framework/core/what-is-new/ef-core-3.0/breaking-changes.md @@ -7,6 +7,7 @@ uid: core/what-is-new/ef-core-3.0/breaking-changes --- # Breaking changes included in EF Core 3.0 + The following API and behavior changes have the potential to break existing applications when upgrading them to 3.0.0. Changes that we expect to only impact database providers are documented under [provider changes](xref:core/providers/provider-log). diff --git a/entity-framework/core/what-is-new/ef-core-3.0/index.md b/entity-framework/core/what-is-new/ef-core-3.0/index.md index 7329a7414f..522bba0a28 100644 --- a/entity-framework/core/what-is-new/ef-core-3.0/index.md +++ b/entity-framework/core/what-is-new/ef-core-3.0/index.md @@ -12,7 +12,7 @@ The following list includes the major new features in EF Core 3.0. As a major release, EF Core 3.0 also contains several [breaking changes](xref:core/what-is-new/ef-core-3.0/breaking-changes), which are API improvements that may have negative impact on existing applications. -## LINQ overhaul +## LINQ overhaul LINQ enables you to write database queries using your .NET language of choice, taking advantage of rich type information to offer IntelliSense and compile-time type checking. But LINQ also enables you to write an unlimited number of complicated queries containing arbitrary expressions (method calls or operations). @@ -21,6 +21,7 @@ How to handle all those combinations is the main challenge for LINQ providers. In EF Core 3.0, we rearchitected our LINQ provider to enable translating more query patterns into SQL, generating efficient queries in more cases, and preventing inefficient queries from going undetected. The new LINQ provider is the foundation over which we'll be able to offer new query capabilities and performance improvements in future releases, without breaking existing applications and data providers. ### Restricted client evaluation + The most important design change has to do with how we handle LINQ expressions that cannot be converted to parameters or translated to SQL. In previous versions, EF Core identified what portions of a query could be translated to SQL, and executed the rest of the query on the client. @@ -29,7 +30,7 @@ This type of client-side execution is desirable in some situations, but in many For example, if EF Core 2.2 couldn't translate a predicate in a `Where()` call, it executed an SQL statement without a filter, transferred all the rows from the database, and then filtered them in-memory: ``` csharp -var specialCustomers = +var specialCustomers = context.Customers .Where(c => c.Name.StartsWith(n) && IsSpecialCustomer(c)); ``` @@ -39,12 +40,12 @@ That may be acceptable if the database contains a small number of rows but can r In EF Core 3.0, we've restricted client evaluation to only happen on the top-level projection (essentially, the last call to `Select()`). When EF Core 3.0 detects expressions that can't be translated anywhere else in the query, it throws a runtime exception. -To evaluate a predicate condition on the client as in the previous example, developers now need to explicitly switch evaluation of the query to LINQ to Objects: +To evaluate a predicate condition on the client as in the previous example, developers now need to explicitly switch evaluation of the query to LINQ to Objects: ``` csharp var specialCustomers = context.Customers - .Where(c => c.Name.StartsWith(n)) + .Where(c => c.Name.StartsWith(n)) .AsEnumerable() // switches to LINQ to Objects .Where(c => IsSpecialCustomer(c)); ``` @@ -57,7 +58,7 @@ Another aspect of the design that changed significantly in 3.0 is that we now al Similarly to client evaluation, if EF Core 3.0 can't translate a LINQ query into a single SQL statement, it throws a runtime exception. But we made EF Core capable of translating many of the common patterns that used to generate multiple queries to a single query with JOINs. -## Cosmos DB support +## Cosmos DB support The Cosmos DB provider for EF Core enables developers familiar with the EF programing model to easily target Azure Cosmos DB as an application database. The goal is to make some of the advantages of Cosmos DB, like global distribution, "always on" availability, elastic scalability, and low latency, even more accessible to .NET developers. The provider enables most EF Core features, like automatic change tracking, LINQ, and value conversions, against the SQL API in Cosmos DB. @@ -72,7 +73,7 @@ EF Core 3.0 takes advantage of a couple of the [new features in C# 8.0](https:// Asynchronous query results are now exposed using the new standard `IAsyncEnumerable` interface and can be consumed using `await foreach`. ``` csharp -var orders = +var orders = from o in context.Orders where o.Status == OrderStatus.Pending select o; @@ -80,12 +81,12 @@ var orders = await foreach(var o in orders.AsAsyncEnumerable()) { Process(o); -} +} ``` See the [asynchronous streams in the C# documentation](https://docs.microsoft.com/dotnet/csharp/whats-new/csharp-8#asynchronous-streams) for more details. -### Nullable reference types +### Nullable reference types When this new feature is enabled in your code, EF Core examines the nullability of reference type properties and applies it to corresponding columns and relationships in the database: properties of non-nullable references types are treated as if they had the `[Required]` data annotation attribute. @@ -105,18 +106,18 @@ See [Working with nullable reference types](xref:core/miscellaneous/nullable-ref ## Interception of database operations -The new interception API in EF Core 3.0 allows providing custom logic to be invoked automatically whenever low-level database operations occur as part of the normal operation of EF Core. For example, when opening connections, committing transactions, or executing commands. +The new interception API in EF Core 3.0 allows providing custom logic to be invoked automatically whenever low-level database operations occur as part of the normal operation of EF Core. For example, when opening connections, committing transactions, or executing commands. -Similarly to the interception features that existed in EF 6, interceptors allow you to intercept operations before or after they happen. When you intercept them before they happen, you are allowed to by-pass execution and supply alternate results from the interception logic. +Similarly to the interception features that existed in EF 6, interceptors allow you to intercept operations before or after they happen. When you intercept them before they happen, you are allowed to by-pass execution and supply alternate results from the interception logic. For example, to manipulate command text, you can create an `IDbCommandInterceptor`: -``` csharp +``` csharp public class HintCommandInterceptor : DbCommandInterceptor { public override InterceptionResult ReaderExecuting( - DbCommand command, - CommandEventData eventData, + DbCommand command, + CommandEventData eventData, InterceptionResult result) { // Manipulate the command text, etc. here... @@ -124,7 +125,7 @@ public class HintCommandInterceptor : DbCommandInterceptor return result; } } -``` +``` And register it with your `DbContext`: @@ -136,7 +137,7 @@ services.AddDbContext(b => b ## Reverse engineering of database views -Query types, which represent data that can be read from the database but not updated, have been renamed to [keyless entity types](xref:core/modeling/keyless-entity-types). +Query types, which represent data that can be read from the database but not updated, have been renamed to [keyless entity types](xref:core/modeling/keyless-entity-types). As they are an excellent fit for mapping database views in most scenarios, EF Core now automatically creates keyless entity types when reverse engineering database views. For example, using the [dotnet ef command-line tool](xref:core/miscellaneous/cli/dotnet) you can type: @@ -187,10 +188,10 @@ public class OrderDetails ## EF 6.3 on .NET Core -This isn't really an EF Core 3.0 feature, but we think it is important to many of our current customers. +This isn't really an EF Core 3.0 feature, but we think it is important to many of our current customers. -We understand that many existing applications use previous versions of EF, and that porting them to EF Core only to take advantage of .NET Core can require a significant effort. -For that reason, we decided to port the newest version of EF 6 to run on .NET Core 3.0. +We understand that many existing applications use previous versions of EF, and that porting them to EF Core only to take advantage of .NET Core can require a significant effort. +For that reason, we decided to port the newest version of EF 6 to run on .NET Core 3.0. For more details, see [what's new in EF 6](xref:ef6/what-is-new/index).