'EF Core Cosmos DB provider doesn't populate id as combination of key and discriminator

I use CosmosDB (Sql Core) + EFCore (3.1.10) + CosmosDb provider (3.1.10).

My entity has property Id (starts with capital latter), discrimination is not turned off.

So, according to this and other articles I expect that id will be populated as a combination of discriminator and Id ("EntityType|IdValue"). However, in my case id is populated just with discriminator value My code: Entity:

public class TestEntity3
{
    public string Id { get; set; }
    public string Prop3 { get; set; }
}

DbContext:

class TestEntity3DbContext : DbContext
{
    public DbSet<TestEntity3> TestEntities3 { get; protected set; } = null!;

    public TestEntity3DbContext(DbContextOptions<TestEntity3DbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.HasDefaultContainer("UnifiedStorage");
        builder.Entity<TestEntity3>(o =>
        {
            o.HasKey(o => o.Id);
            o.HasPartitionKey(o => o.Id);
        });
    }
}

To create a record I use following code:

        _testEntityContext.TestEntities3.Add(new TestEntity3()
        {
            Id = Guid.NewGuid().ToString(),
            Prop3 = "Hello"
        });
        await _testEntityContext.SaveChangesAsync();

As a result I see this record (several fields were removed):

{
"Id": "fe2b7107-f9d0-4c7d-a594-f6bccaab36cd",
"Discriminator": "TestEntity3",
"Prop3": "Hello",
"id": "TestEntity3",
"_ts": 1605731991

}

So, there is id = "TestEntity3", but it should be "TestEntity3|fe2b7107-f9d0-4c7d-a594-f6bccaab36cd"

Did I miss something? Does anybody know what's wrong?

Thank you in advance.



Solution 1:[1]

I have seen that as well and believe it is by design.

This happens when you are using the same attribute for partition key and primary key. The idea is that id should be unique within each partition key.

In this case you are saying that each partition key is unique (i.e. you have exactly one entity in each partition) so there is no reason to use the id for anything except keeping track of the discriminator.

Documentation about Cosmos EF modelling can be found here.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1