0

Given this kind of code:

public class Topic
{
    public enum Category
    {
        Language,
        Science
    }

    public Category Name { get; set; }
    public string Description { get; set; } = null!;
}

public class MyEntity
{
    public List<Topic>? Topics { get; set; } = null!;
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<MyEntity>(
        b =>
        {
            b.Property(e => e.Topics)
                .HasConversion(
                    v => JsonSerializer.Serialize(v, default),
                    v => JsonSerializer.Deserialize<List<Topic>>(v, default));
        });
}

When storing this data:

{
    "topics":[{
        "name": "language",
        "description": "HelloWorld"
    }]
}

It gets stored as:

[{"Name":0,"Description":"HelloWorld"}]

How can I store Category as a string (Language instead of 0)?

jpen
  • 2,129
  • 5
  • 32
  • 56
  • 3
    This has nothing to do with EF (Core). It's all about Json serialization, please use correct tags. – Ivan Stoev Aug 01 '22 at 13:29
  • Thanks @Charlieface. I know how to store `Category` as string if `MyEntity` contained it as a simple property. In my case it's wrapped in `Topic` and stored in a list. I'm not sure how to apply the answer in the link you provided... – jpen Aug 01 '22 at 13:36
  • Sounds like you need https://learn.microsoft.com/en-us/dotnet/api/system.text.json.serialization.jsonstringenumconverter?view=net-6.0 – Charlieface Aug 01 '22 at 13:39
  • Enum values in c# are always numbers to save memory. If you want a string you should be using a Dictionary which contains a KEY and Value. the Value can be any type. A enum always has a value as a number. – jdweng Aug 01 '22 at 13:53
  • Thanks again @Charlieface. Applying `[JsonConverter(typeof(JsonStringEnumConverter))]` to `public Category Name { get; set; }` seems to have done the trick. – jpen Aug 01 '22 at 13:54

0 Answers0