Skip to content

Commit

Permalink
[release/9.0] Fix Cosmos enum partition keys (#34922)
Browse files Browse the repository at this point in the history
Fixes #34911
  • Loading branch information
roji authored Oct 17, 2024
1 parent 88cfe49 commit 4147693
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,16 @@ public static class PartitionKeyBuilderExtensions
/// </summary>
public static PartitionKeyBuilder Add(this PartitionKeyBuilder builder, object? value, IProperty? property)
{
if (value is not null && value.GetType() is var clrType && clrType.IsInteger() && property is not null)
{
var unwrappedType = property.ClrType.UnwrapNullableType();
value = unwrappedType.IsEnum
? Enum.ToObject(unwrappedType, value)
: unwrappedType == typeof(char)
? Convert.ChangeType(value, unwrappedType)
: value;
}

var converter = property?.GetTypeMapping().Converter;
if (converter != null)
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace Microsoft.EntityFrameworkCore.Query;

#nullable disable

public class AdHocMiscellaneousQueryCosmosTest : NonSharedModelTestBase
{
#region 34911

[ConditionalFact]
public virtual async Task Enum_partition_key()
{
var contextFactory = await InitializeAsync<Context34911>(
onModelCreating: b => b.Entity<Context34911.Member>().HasPartitionKey(d => d.MemberType),
seed: async context =>
{
context.Members.Add(new Context34911.Member { MemberType = Context34911.MemberType.Admin, Name = "Some Admin" });
await context.SaveChangesAsync();
});

await using (var context = contextFactory.CreateContext())
{
var admin = await context.Members.Where(p => p.MemberType == Context34911.MemberType.Admin).SingleAsync();
Assert.Equal("Some Admin", admin.Name);
}
}

protected class Context34911(DbContextOptions options) : DbContext(options)
{
public DbSet<Member> Members { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
=> modelBuilder.Entity<Member>().HasData(new Member { Id = 1, Name = "Product 1" });

public class Member
{
public int Id { get; set; }
public MemberType MemberType { get; set; }
public string Name { get; set; }
}

public enum MemberType
{
User,
Admin
}
}

#endregion 34911

protected override string StoreName
=> "AdHocMiscellaneousQueryTests";

protected override DbContextOptionsBuilder AddOptions(DbContextOptionsBuilder builder)
=> builder.ConfigureWarnings(b => b.Ignore(CosmosEventId.NoPartitionKeyDefined));

protected override ITestStoreFactory TestStoreFactory
=> CosmosTestStoreFactory.Instance;
}

0 comments on commit 4147693

Please sign in to comment.