dotnet / dotnet/efcore

JsonB enum column with JsonStringEnumConverter is handled as (casted to) integer during projection

Open
#35,650 5 comments 0 reactions 0 assignees View on GitHub
Dominant language
C#
Stars
14.8k
Forks
3.4k
PR merge metrics
PR metrics pending

Description

In my business logic I'm having event registrations and optional AutoApprovedInfo on it which contains optional enum value AutoStatusRule.
Creating entity and saving it into the database creates expected AutoApprovedInfo entry with enum as a string, e.g.
**{"Rule": "AnotherRule"}**

Now I'm trying to calculate the KPIs, specifically, how many times each rule was applied

`e.Registrations.Where(r => r.AutoApprovedInfo.Rule != null).GroupBy(i => i.AutoApprovedInfo.Rule).Select(i => new { a = i.Key, c = i.Count() });`

which crashes and in the log I'm seing that e.f. core tries to cast AutoStatusRule to integer which can't work.
Can I avoid this CAST or somehow convert it to enum or string on the DB side? I'm not registering my enums in postgres.

The relevant part of the generated query is

```
SELECT d24."Key" AS a, count(*)::int AS c
FROM (
SELECT CAST(d23."AutoApprovedInfo" ->> 'Rule' AS integer) AS "Key"
FROM "EventRegistration" AS d23
WHERE d25."Id" = d23."EventId" AND d23."AutoApprovedInfo" ->> 'Rule' IS NOT NULL
) AS d24
```

My simplified code

```
public class EventRegistration
{
[Key]
public int Id { get; set; }

[Column(TypeName = "jsonb")]
public AutoApprovedInfo? AutoApprovedInfo { get; set; }
}
```

```
public class AutoApprovedInfo
{
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
[JsonConverter(typeof(JsonStringEnumConverter))]
public AutoStatusRule? Rule { get; set; }
}
```

public enum AutoStatusRule
{
Rule1,
AnotherRule,
SomeOtherRule
}

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.