Skip to content

Conflicting partition key filter is ignored in ReadItem case #38238

@AndriySvyryd

Description

@AndriySvyryd

Bug description

The below code results in ReadItem with the partition key from WithPartitionKey, but it should've thrown an exception.

Your code

using System.Reflection;
using Microsoft.Azure.Cosmos;
using Microsoft.EntityFrameworkCore;

var databaseName = $"EfCoreCosmosWithPartitionKeyBypass";
const string victimPartitionKey = "PK1";
const string filteredPartitionKey = "PK2";
const string sharedId = "shared-id";

await using var setupContext = new ReproContext(databaseName);
await setupContext.Database.EnsureDeletedAsync();
await setupContext.Database.EnsureCreatedAsync();

setupContext.AddRange(
    new SinglePartitionKeyEntity
    {
        Id = sharedId,
        PartitionKey = victimPartitionKey,
        Payload = "VictimPayload",
    },
    new SinglePartitionKeyEntity
    {
        Id = sharedId,
        PartitionKey = filteredPartitionKey,
        Payload = "FilteredPayload",
    });

await setupContext.SaveChangesAsync();

await using var projectionContext = new ReproContext(databaseName);
var projectionQuery = projectionContext.Entities
    .WithPartitionKey(victimPartitionKey)
    .Where(e => e.Id == sharedId && e.PartitionKey == filteredPartitionKey)
    .Select(e => e.PartitionKey);
Console.WriteLine($"{projectionQuery.ToQueryString().Replace(Environment.NewLine, " ")}");

var projectedPartitionKey = await projectionQuery.SingleOrDefaultAsync();

Console.WriteLine($"projectedPartitionKey={projectedPartitionKey ?? "<null>"}");

class ReproContext(string databaseName) : DbContext
{
    public DbSet<SinglePartitionKeyEntity> Entities => Set<SinglePartitionKeyEntity>();

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder.UseCosmos();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<SinglePartitionKeyEntity>()
            .ToContainer("SinglePartitionKeyEntity")
            .HasPartitionKey(e => e.PartitionKey)
            .HasKey(e => new { e.Id, e.PartitionKey });
    }
}

sealed class SinglePartitionKeyEntity
{
    public string Id { get; set; } = null!;
    public string PartitionKey { get; set; } = null!;
    public string Payload { get; set; } = null!;
}

Stack traces


Verbose output


EF Core version

10.0.0

Database provider

No response

Target framework

No response

Operating system

No response

IDE

No response

Metadata

Metadata

Assignees

Type

No fields configured for Bug.

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions