Convert Enum From String To Int In DB Then Back To String - Entity Framework Core 3

asp.net-core-webapi c# entity-framework entity-framework-core enums

Question

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://docs.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.

1
0
12/28/2019 4:33:36 AM

Accepted Answer

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.

1
12/28/2019 5:42:22 AM

Popular Answer

This will return the enum string:

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


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow