Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion entity-framework/core/cli/dotnet.md
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,10 @@ Options:

| Option | Description |
|:------------------------------------------|:---------------------------------------------------------------------------------------------------------------------------------|
| <nobr>`--connection <CONNECTION>`</nobr> | The connection string to the database. Defaults to the one specified in `AddDbContext` or `OnConfiguring`. |
| <nobr>`--connection <CONNECTION>`</nobr> | The connection string to the database. Defaults to the one specified in `AddDbContext` or `OnConfiguring`. |
| <nobr>`--add`</nobr> | Creates a new migration and applies it to the database in a single step. Uses Roslyn to compile the migration at runtime. When specified, the `<MIGRATION>` argument is required and provides the name for the new migration. Added in EF Core 11. |
| <nobr>`--output-dir <PATH>`</nobr> | The directory to put migration files in. Paths are relative to the target project directory. Requires `--add`. Added in EF Core 11. |
| <nobr>`--namespace <NAMESPACE>`</nobr> | The namespace to use for the generated migration classes. Requires `--add`. Added in EF Core 11. |

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

Expand All @@ -163,6 +166,13 @@ dotnet ef database update InitialCreate
dotnet ef database update 20180904195021_InitialCreate --connection your_connection_string
```

The following examples create a new migration and apply it to the database in one step:

```dotnetcli
dotnet ef database update InitialCreate --add
dotnet ef database update AddProducts --add --output-dir Migrations/Products --namespace MyApp.Migrations
```

## `dotnet ef dbcontext info`

Gets information about a `DbContext` type.
Expand Down
9 changes: 9 additions & 0 deletions entity-framework/core/cli/powershell.md
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,9 @@ Updates the database to the last migration or to a specified migration.
|:------------------------------------|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| <nobr>`-Migration <String>`</nobr> | The target migration. Migrations may be identified by name or by ID. The number 0 is a special case that means *before the first migration* and causes all migrations to be reverted. If no migration is specified, the command defaults to the last migration. |
| <nobr>`-Connection <String>`</nobr> | The connection string to the database. Defaults to the one specified in `AddDbContext` or `OnConfiguring`. |
| <nobr>`-Add`</nobr> | Creates a new migration and applies it to the database in a single step. Uses Roslyn to compile the migration at runtime. When specified, a migration name is required and provides the name for the new migration. Added in EF Core 11. |
| <nobr>`-OutputDir <String>`</nobr> | The directory to put migration files in. Paths are relative to the target project directory. Requires `-Add`. Added in EF Core 11. |
| <nobr>`-Namespace <String>`</nobr> | The namespace to use for the generated migration classes. Requires `-Add`. Added in EF Core 11. |

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

Expand All @@ -335,6 +338,12 @@ Update-Database InitialCreate
Update-Database 20180904195021_InitialCreate -Connection your_connection_string
```

The following example creates a new migration and applies it to the database in one step:

```powershell
Update-Database -Migration InitialCreate -Add
```

## Additional resources

* [Migrations](xref:core/managing-schemas/migrations/index)
Expand Down
31 changes: 31 additions & 0 deletions entity-framework/core/managing-schemas/migrations/managing.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,37 @@ Add-Migration InitialCreate -OutputDir Your\Directory

***

## Create and apply a migration in one step

> [!NOTE]
> This feature was added in EF Core 11.

The `dotnet ef database update` command supports creating and applying a migration in a single step using the `--add` option. This uses Roslyn to compile the migration at runtime, enabling scenarios like .NET Aspire and containerized applications where the application cannot be stopped and rebuilt:

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

```dotnetcli
dotnet ef database update InitialCreate --add
```

The same options available for `dotnet ef migrations add` can be used:

```dotnetcli
dotnet ef database update AddProducts --add --output-dir Migrations/Products --namespace MyApp.Migrations
```

### [Visual Studio](#tab/vs)

```powershell
Update-Database -Migration InitialCreate -Add
```

***

This command scaffolds a new migration with the specified name, compiles it using Roslyn, and immediately applies it to the database. The migration files are still saved to disk for source control and future recompilation.

If no pending model changes are detected, the command applies any existing pending migrations without creating a new one.

## Customize migration code

While EF Core generally creates accurate migrations, you should always review the code and make sure it corresponds to the desired change; in some cases, it is even necessary to do so.
Expand Down
62 changes: 61 additions & 1 deletion entity-framework/core/modeling/indexes.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
title: Indexes - EF Core
description: Configuring indexes in an Entity Framework Core model
author: SamMonoRT
ms.date: 10/1/2021
ms.date: 06/09/2026
uid: core/modeling/indexes
---
# Indexes
Expand Down Expand Up @@ -40,6 +40,58 @@ An index can also span more than one column:

Indexes over multiple columns, also known as *composite indexes*, speed up queries which filter on index's columns, but also queries which only filter on the *first* columns covered by the index. See the [performance docs](xref:core/performance/efficient-querying#use-indexes-properly) for more information.

## Indexes on complex type properties

Starting with EF Core 11.0, indexes can use scalar properties nested inside [complex types](xref:core/what-is-new/ef-core-10.0/whatsnew#complex-types):

```csharp
modelBuilder.Entity<Customer>()
.HasIndex(c => c.Address.PostalCode);
```

Composite indexes can mix regular entity properties and complex type properties:

```csharp
modelBuilder.Entity<Customer>()
.HasIndex(c => new { c.Region, c.Address.PostalCode });
```

The same paths can be specified by name:

```csharp
modelBuilder.Entity<Customer>()
.HasIndex("Address.PostalCode");
```

For complex types mapped to JSON columns, providers may also support indexing paths inside the JSON document:

```csharp
modelBuilder.Entity<Customer>()
.ComplexProperty(c => c.Address, b => b.ToJson());

modelBuilder.Entity<Customer>()
.HasIndex("Address.PostalCode");
```

Indexes over complex collections use collection path syntax. `[]` represents all elements, while `[0]`, `[1]`, and so on represent a specific element:

```csharp
modelBuilder.Entity<Order>()
.ComplexCollection(o => o.Items, b => b.ToJson());

modelBuilder.Entity<Order>()
.HasIndex("Items[].Sku");
```

The same index can be configured with a lambda expression using `Select`:

```csharp
modelBuilder.Entity<Order>()
.HasIndex(o => o.Items.Select(i => i.Sku));
```

Support for JSON-path indexes depends on the database provider. For example, the SQL Server provider creates SQL Server JSON indexes where supported, while the Azure Cosmos DB provider emits the configured paths into the container indexing policy.

## Index uniqueness

By default, indexes aren't unique: multiple rows are allowed to have the same value(s) for the index's column set. You can make an index unique as follows:
Expand Down Expand Up @@ -148,6 +200,14 @@ In the following example, the `Url` column is part of the index key, so any quer

[!code-csharp[Main](../../../samples/core/Modeling/IndexesAndConstraints/FluentAPI/IndexInclude.cs?name=IndexInclude&highlight=5-9)]

Starting with EF Core 11.0, SQL Server included columns can also refer to scalar properties nested inside complex types:

```csharp
modelBuilder.Entity<Customer>()
.HasIndex(c => c.Name)
.IncludeProperties(c => c.Address.City);
```

## Check constraints

Check constraints are a standard relational feature that allows you to define a condition that must hold for all rows in a table; any attempt to insert or modify data that violates the constraint will fail. Check constraints are similar to non-null constraints (which prohibit nulls in a column) or to unique constraints (which prohibit duplicates), but allow arbitrary SQL expression to be defined.
Expand Down
20 changes: 19 additions & 1 deletion entity-framework/core/modeling/keys.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
title: Keys - EF Core
description: How to configure keys for entity types when using Entity Framework Core
author: AndriySvyryd
ms.date: 10/14/2022
ms.date: 06/09/2026
uid: core/modeling/keys
---
# Keys
Expand Down Expand Up @@ -53,6 +53,24 @@ public class Car

***

## Keys on complex type properties

Starting with EF Core 11.0, keys can use scalar properties nested inside non-collection [complex types](xref:core/what-is-new/ef-core-10.0/whatsnew#complex-types).

```csharp
modelBuilder.Entity<Customer>()
.HasKey(c => c.CustomerId.Value);
```

The same path can be specified by name:

```csharp
modelBuilder.Entity<Customer>()
.HasKey("CustomerId.Value");
```

Complex properties on the path to a key property are required. Keys can't traverse complex collections or nullable complex properties.

## Value generation

For non-composite numeric and GUID primary keys, EF Core sets up value generation for you by convention. For example, a numeric primary key in SQL Server is automatically set up to be an IDENTITY column. For more information, see [the documentation on value generation](xref:core/modeling/generated-properties) and [guidance for specific inheritance mapping strategies](xref:core/modeling/inheritance#key-generation).
Expand Down
43 changes: 42 additions & 1 deletion entity-framework/core/providers/cosmos/modeling.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
title: Modeling - Azure Cosmos DB Provider - EF Core
description: Configuring the model with the Azure Cosmos DB EF Core Provider
author: SamMonoRT
ms.date: 09/26/2024
ms.date: 06/09/2026
uid: core/providers/cosmos/modeling
---
# Configuring the model with the EF Core Azure Cosmos DB Provider
Expand Down Expand Up @@ -67,6 +67,47 @@ If you don't configure a partition key with EF, a warning will be logged at star

Once your partition key properties are properly configured, you can provide values for them in queries; see [Querying with partition keys](xref:core/providers/cosmos/querying#partition-keys) for more information.

## Indexing policy

Starting with EF Core 11.0, the Azure Cosmos DB provider emits more of the EF model's index configuration into the container [indexing policy](/azure/cosmos-db/index-policy).

By default, Azure Cosmos DB automatically indexes all properties. You can configure this automatic indexing policy and exclude individual paths:

```csharp
modelBuilder.Entity<Order>()
.HasAutomaticIndexing()
.Except("/InternalNotes/?");
```

To index only explicitly configured paths, configure indexes with `HasIndex`. Automatic indexing is disabled automatically as soon as any single-property index is defined, so there is no need to call `HasAutomaticIndexing(false)` explicitly:

```csharp
modelBuilder.Entity<Order>(b =>
{
b.HasIndex(o => o.OrderNumber);
b.HasIndex(o => new { o.CustomerId, o.OrderDate });
});
```

When automatic indexing is enabled, single-property indexes are already covered by the default `/*` included path and aren't emitted separately. Composite, vector, and full-text indexes are always emitted.

Indexes can also traverse complex type properties and complex collections. In a string path, `[]` represents all elements of a collection:

```csharp
modelBuilder.Entity<Order>(b =>
{
b.ComplexCollection(o => o.Items);
b.HasIndex("Items[].Sku");
});
```

The same index can be configured with a lambda expression:

```csharp
modelBuilder.Entity<Order>()
.HasIndex(o => o.Items.Select(i => i.Sku));
```

## Discriminators

Since multiple entity types may be mapped to the same container, EF Core always adds a `$type` discriminator property to all JSON documents you save (this property was called `Discriminator` before EF 9.0); this allows EF to recognize documents being loaded from the database, and materialize the right .NET type. Developers coming from relational databases may be familiar with discriminators in the context of [table-per-hierarchy inheritance (TPH)](xref:core/modeling/inheritance#table-per-hierarchy-and-discriminator-configuration); in Azure Cosmos DB, discriminators are used not just in inheritance mapping scenarios, but also because the same container can contain completely different document types.
Expand Down
32 changes: 31 additions & 1 deletion entity-framework/core/providers/sql-server/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
title: Microsoft SQL Server Database Provider - EF Core
description: Documentation for the database provider that allows Entity Framework Core to be used with Microsoft SQL Server
author: AndriySvyryd
ms.date: 11/15/2021
ms.date: 06/09/2026
uid: core/providers/sql-server/index
---
# Microsoft SQL Server EF Core Database Provider
Expand Down Expand Up @@ -113,6 +113,36 @@ To configure EF with a compatibility level, use `UseCompatibilityLevel()` as fol
optionsBuilder.UseSqlServer("<CONNECTION STRING>", o => o.UseCompatibilityLevel(170));
```

## JSON indexes

Starting with EF Core 11.0, the SQL Server provider can create and scaffold [SQL Server JSON indexes](/sql/t-sql/statements/create-json-index-transact-sql) for paths inside complex types mapped to JSON columns.

For example, the following maps a complex type to a JSON column and creates a JSON index over a nested property:

```csharp
modelBuilder.Entity<Customer>()
.ComplexProperty(c => c.Contact, b => b.ToJson().HasColumnType("json"));

modelBuilder.Entity<Customer>()
.HasIndex("Contact.Address.City");
```

When SQL Server JSON indexes are supported, migrations generate SQL similar to:

```sql
CREATE JSON INDEX [IX_Customers_Contact_Address_City]
ON [Customers]([Contact]) FOR (N'$.Address.City');
```

Multiple paths inside the same JSON column can be indexed together:

```csharp
modelBuilder.Entity<Customer>()
.HasIndex(["Contact.Address.City", "Contact.PhoneNumber"]);
Comment thread
AndriySvyryd marked this conversation as resolved.
Comment thread
AndriySvyryd marked this conversation as resolved.
```
Comment thread
AndriySvyryd marked this conversation as resolved.
Comment thread
AndriySvyryd marked this conversation as resolved.

Paths through JSON arrays can use numeric indexers, for example `Orders[0].Number`. SQL Server JSON indexes don't support wildcard indexes over every array element.

## Connection resiliency

EF includes functionality for automatically retrying failed database commands; for more information, [see the documentation](xref:core/miscellaneous/connection-resiliency). When using <xref:Microsoft.EntityFrameworkCore.SqlServerDbContextOptionsExtensions.UseAzureSql*> and <xref:Microsoft.EntityFrameworkCore.SqlServerDbContextOptionsExtensions.UseAzureSynapse*>, connection resiliency is automatically set up with the appropriate settings specific for those databases. Otherwise, when using <xref:Microsoft.EntityFrameworkCore.SqlServerDbContextOptionsExtensions.UseSqlServer*>, configure the provider with <xref:Microsoft.EntityFrameworkCore.Infrastructure.SqlEngineDbContextOptionsBuilder.EnableRetryOnFailure*> as shown in the connection resiliency documentation.
Expand Down
32 changes: 18 additions & 14 deletions entity-framework/core/providers/sql-server/vector-search.md
Original file line number Diff line number Diff line change
Expand Up @@ -196,25 +196,31 @@ SqlVector<float> queryEmbedding = ...;
var results = await context.Articles
// Perform full-text search
.FreeTextTable<Article, int>(textualQuery, topN: k)
.Join(
context.Articles,
fts => fts.Key,
a => a.Id,
(fts, a) => new { Article = a, fts.Rank })
// Perform vector (semantic) search, joining the results of both searches together
.LeftJoin(
.FullJoin(
context.Articles.VectorSearch(b => b.Embedding, queryEmbedding, "cosine")
.OrderBy(r => r.Distance)
.Take(k)
.WithApproximate(),
fts => fts.Key,
fts => fts.Article.Id,
vs => vs.Value.Id,
(fts, vs) => new
{
Article = vs.Value,
FullTextRank = fts.Rank,
VectorDistance = (double?)vs.Distance
Article = fts != null ? fts.Article : vs.Value,
FullTextRank = fts == null ? null : (int?)fts.Rank,
VectorDistance = vs == null ? null : (double?)vs.Distance
})
// Apply Reciprocal Rank Fusion (RRF) to combine the results
.Select(x => new
{
x.Article,
RrfScore = (1.0 / (k + x.FullTextRank)) + (1.0 / (k + x.VectorDistance) ?? 0.0)
RrfScore = (x.FullTextRank == null ? 0.0 : 1.0 / (k + x.FullTextRank.Value))
+ (x.VectorDistance == null ? 0.0 : 1.0 / (k + x.VectorDistance.Value))
})
Comment thread
AndriySvyryd marked this conversation as resolved.
Comment thread
AndriySvyryd marked this conversation as resolved.
.OrderByDescending(x => x.RrfScore)
.Take(10)
Expand All @@ -225,19 +231,17 @@ var results = await context.Articles
This query:

1. Performs a full-text search on `Article`
2. Performs a vector search on `Article` and combines the results to the full-text search results via a LEFT JOIN
2. Performs a vector search on `Article` and combines the results with the full-text search results via a FULL JOIN
3. Calculates the RRF score by combining both the full text and the semantic ranking
4. Orders by RRF score, takes the desired number of results and projects out the original `Article` entities.

> [!NOTE]
> Rather than using a LEFT JOIN, a FULL OUTER JOIN would be more suitable for this scenario; this would allow highly-ranking results from either search side to be included in the final result, even if that result does not appear at all on the other side. With the above LEFT JOIN approach, if a result has a very high vector similarity score, it never gets included in the final result if that result doesn't also have a high full-text score. However, EF doesn't currently support FULL OUTER JOIN; upvote [#37633](https://github.com/dotnet/efcore/issues/37633) if this is something you'd like to see supported.

The query produces the following SQL:

```sql
SELECT TOP(@__p_4) [a0].[Id], [a0].[Content], [a0].[Title]
SELECT TOP(@__p_4) COALESCE([a].[Id], [t].[Id]) AS [Id], COALESCE([a].[Content], [t].[Content]) AS [Content], COALESCE([a].[Title], [t].[Title]) AS [Title]
FROM FREETEXTTABLE([Articles], *, @__textualQuery_0, @__k_1) AS [f]
LEFT JOIN (
INNER JOIN [Articles] AS [a] ON [f].[KEY] = [a].[Id]
FULL JOIN (
SELECT TOP(@__k_1) WITH APPROXIMATE [a].[Id], [a].[Content], [a].[Title], [v].[Distance]
FROM VECTOR_SEARCH(
TABLE = [Articles] AS [a],
Expand All @@ -246,6 +250,6 @@ LEFT JOIN (
METRIC = 'cosine'
) AS [v]
ORDER BY [v].[Distance]
) AS [t] ON [f].[KEY] = [t].[Id]
ORDER BY 1.0E0 / CAST(@__k_1 + [f].[RANK] AS float) + ISNULL(1.0E0 / (CAST(@__k_1 AS float) + [t].[Distance]), 0.0E0) DESC
) AS [t] ON [a].[Id] = [t].[Id]
ORDER BY ISNULL(1.0E0 / CAST(@__k_1 + [f].[RANK] AS float), 0.0E0) + ISNULL(1.0E0 / (CAST(@__k_1 AS float) + [t].[Distance]), 0.0E0) DESC
```
2 changes: 2 additions & 0 deletions entity-framework/core/providers/sqlite/functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ group.Min(x => x.Property) | MIN(Property)
group.Sum(x => x.Property) | SUM(Property)
group.Sum(x => x.DecimalProperty) | ef_sum(DecimalProperty) | EF Core 9.0
string.Concat(group.Select(x => x.Property)) | group_concat(Property, '')
string.Concat(group.OrderBy(x => x.Other).Select(x => x.Property)) | group_concat(Property, '' ORDER BY Other) | EF Core 11.0
string.Join(separator, group.Select(x => x.Property)) | group_concat(Property, @separator)
string.Join(separator, group.OrderBy(x => x.Other).Select(x => x.Property)) | group_concat(Property, @separator ORDER BY Other) | EF Core 11.0

## Binary functions

Expand Down
Loading
Loading