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.

1

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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!
Do you have a (preferably microsoft) source saying "EF Core stores Enums as Integer" ? I need it to convince other developpers to use enums instead of magic numbers in their entities
@Inspi I think for persuading to not using magic numbers you don't need an EF-related reference, Either integer constants or Enums can be used for this purpose depending the case
0

This will return the enum string:

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

1 Comment

Thank you for the answer, but this wasn't what I was asking. I appreciate it though!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.