0

I have an Enum similar to this:

    public enum Type
    {
        TypeA,
        TypeB,
        TypeC
    }

I have this using Fluent API and Entity Framework 3.0:

    builder.Entity<Element>()
        .Property(p => p.Type)
        .HasConversion<int>();

This converts the string coming in and saves it in the DB as an int. However, when I do a query to pull it out of the DB it is staying an int.

I have read the docs but I cannot seem to understand:

How do I take the string of the Enum - convert it to an int for the DB - then receive a string when I query the DB?

I thought maybe it was using EnumToNumberConverter but it takes two arguments and I have no idea what the second argument should be. As seen in these docs: https://learn.microsoft.com/en-us/ef/core/modeling/value-conversions

Can anyone please give me a concrete example of how I convert an Enum's string to integer when storing in the DB and then when querying it get handed the Enum's string again?

Thank you.

  • Does this answer your question? [Getting attributes of Enum's value](https://stackoverflow.com/questions/1799370/getting-attributes-of-enums-value) – Hameed Syed Dec 28 '19 at 04:49

2 Answers2

3

You don't need using convertors, EF Core stores Enums as an Integer. So, using .HasConversion<int>(); is not needed anymore. EF Core reads this value as an Integer and casts it to the Type when you send a query. Therefore, you have a Type that you can use Type.Sample.ToString() to using string value.

Hadi Samadzad
  • 1,480
  • 2
  • 13
  • 22
  • Thank you for the answer. You're right, I don't need that. It was my front end TypeScript Enum that was casting it back to a number. So it was coming out my API a string again and then in the front end a TS Enum was casting it back to a number. Now to figure out how not to cast it back to a number. I appreciate your help! – Eric Belisle Giddings Dec 28 '19 at 13:47
1

This will return the enum string:

enum E : int
{
    Element1 = 42
}
//...
int i = 42;
string s = ((E)i).ToString();// returns "Element1"
//...
beothunder
  • 551
  • 2
  • 14