skip to content

In EF Core 10's Azure Cosmos DB provider, why do partition keys and the lack of cross-document joins change how you model and query data?

level: seniorimportance: nice to knowfreq 18%

answer

  1. one container per context by default
  2. HasPartitionKey, up to three properties
  3. WithPartitionKey or an equality in Where
  4. id plus partition key: point read
  5. Include only for embedded data

basics

~20 s

Cosmos DB scales by partition key, so EF Core's Cosmos provider makes the partition key part of each entity's key and targets one partition only when a query supplies it; it cannot join documents, so related data must be embedded in one document.

solid answer

~50 s

With `UseCosmos`, every entity type shares one container named after the context unless `ToContainer` moves it, and `HasPartitionKey` picks the property, or since EF Core 9 up to three properties, that spreads documents across partitions. EF's key for an entity then includes the partition key, so `FindAsync` needs both, and a query is scoped to one partition only when its `Where` compares the partition-key properties for equality or it calls `WithPartitionKey`; otherwise it fans out across all partitions. With the `id` and the full partition key, EF issues a point read instead of a query. There are no joins across documents: such a query throws, and `Include` works only for data embedded in the same document, so you model with owned types and denormalize. Since EF Core 9, synchronous calls throw, the discriminator property is `$type`, and the `id` no longer contains the discriminator.

code

csharp · 15 lines
csharp
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<AppointmentRecord>(b =>
    {
        b.ToContainer("Appointments");
        b.HasPartitionKey(a => new { a.ClinicId, a.PatientId });
        b.OwnsMany(a => a.Notes);          // embedded in the same document
    });
}

// one patient's history at one clinic: a single-partition query
var history = await db.AppointmentRecords
    .WithPartitionKey(clinicId, patientId)
    .Where(a => a.StartsAt >= since)
    .ToListAsync();

go deeper

for a junior

Recall that the Cosmos provider stores documents in containers split by a partition key, and that it cannot join documents.

for a middle

Explain how HasPartitionKey, WithPartitionKey and point reads decide which partitions a query touches, and why Include needs embedded data.

for a senior

Show how you would choose a partition key from the real read paths, model embedded data and spot cross-partition queries in the logs.

for a principal

Weigh a document store against a relational one for each bounded context, given joins, transactions and how the data will be read.

## A document store behind a familiar API The **Azure Cosmos DB** provider (`Microsoft.EntityFrameworkCore.Cosmos`, configured with `UseCosmos`) gives Cosmos DB for NoSQL the usual `DbContext`, `DbSet<T>` and LINQ surface. Underneath, each entity is a **JSON document** in a **container**, and a container is split into **partitions** by a partition key. EF Core does not hide those differences; it exposes them, and the model has to follow. Picture the clinic group keeping its appointment history, a write-heavy and read-by-patient workload, in Cosmos DB while the core app stays relational. ## Containers and partition keys - By default **all entity types share one container**, named after the context type; `HasDefaultContainer` renames it and `ToContainer` moves an entity type into its own. - `HasPartitionKey(a => a.ClinicId)` sets the partition key. Since **EF Core 9** it accepts up to **three properties** for a hierarchical key, such as `ClinicId`, then `PatientId`. - The partition key is defined per container, so entity types sharing a container must share the partition-key properties. - EF's notion of an entity's **key includes the partition key**, because two documents may share an `id` in different partitions. `FindAsync` therefore needs both the id and the partition-key values. ## How a query finds its partitions | Query shape | How EF executes it | |---|---| | `id` and every partition-key value, nothing else | a **point read** (`ReadItem`), the cheapest operation | | equality on all partition-key properties in `Where`, or `WithPartitionKey(...)` | a query against one partition | | equality on a leading part of a hierarchical key | a query against the matching sub-partitions | | no partition-key equality | a **cross-partition** query that fans out to every partition | Since EF Core 9 the provider lifts partition-key equalities out of `Where` by itself; `WithPartitionKey` makes the intent explicit and was often needed before 9. The query log shows which partition a query used, so check it for hot paths. ## No joins: embed instead Documents cannot be joined. A query that needs a join across documents throws ("Joins across documents aren't supported in Cosmos"), and `Include` works only for a navigation **embedded in the same document**; any other include throws as well. The modelling consequences: 1. Related entity types are **owned by default** in this provider and stored inside the owner's document, so a patient's appointments can live in the patient document. 2. Data read together is **denormalized** into one document rather than normalized across many. 3. A real reference to another document is loaded with a **second query**, by id and partition key. ## Other differences from relational providers - **No migrations.** There is no schema; `EnsureCreatedAsync` creates the containers, and evolving document shapes is the application's job. - **Async only.** The Cosmos SDK has no synchronous I/O, and since EF Core 9 synchronous calls such as `ToList()` or `SaveChanges()` throw. - **Discriminator and id.** Since EF Core 9 every document carries a `$type` discriminator (it was `Discriminator`), and the `id` no longer embeds the discriminator; `HasDiscriminatorInJsonId()` restores the older format. - **Indexes and constraints** in the model are ignored; Cosmos DB indexes documents by its own policy. - **No cross-document transactions** like a relational `BeginTransaction`. ## Reading the provider's log EF's Cosmos log lines show how each operation ran. A point read appears as `Executed ReadItem` with the container, the id and the partition, while a query appears as `Executed ReadNext` with the partition it targeted, if any, and the SQL that ran. Each line also reports the request charge in request units, so the log is where you confirm that a hot query really stays inside one partition before it reaches production traffic. ## Choosing the clinic's partition key A hierarchical key of `ClinicId` and `PatientId` makes the common reads, one patient's history at one clinic, single-partition or point reads, while a clinic-wide report becomes a cross-partition query run rarely. A key nobody filters on would turn every read into a fan-out.

  • How do you make EF Core's Cosmos provider use a point read instead of a query?
    Supply the `id` and every partition-key value and nothing else, for example `SingleAsync(a => a.Id == id && a.ClinicId == clinicId && a.PatientId == patientId)` or `FindAsync` with the key and partition-key values. EF then issues a `ReadItem` call, which the docs describe as the most efficient and cheapest way to fetch one document.
  • What happens when code written for SQL Server calls ToList() on a Cosmos query in EF Core 10?
    It throws. The Cosmos SDK supports only asynchronous I/O, and since EF Core 9 the provider no longer blocks on async calls for synchronous APIs; it reports the `SyncNotSupported` event as an error. Use `ToListAsync()` and `SaveChangesAsync()` throughout.

  • Include can load related documents from another container like a relational join.
  • A query without the partition key still reads only one partition.
  • dotnet ef migrations add creates the Cosmos containers and their schema.
  • Synchronous SaveChanges works on Cosmos in EF Core 10 by blocking on the async call.
  • Each entity type can choose its own partition key inside a shared container.

Assumes EF Core 10; since EF Core 9 the Cosmos provider extracts partition keys from Where, supports hierarchical keys, throws on synchronous I/O and writes a $type discriminator.