Reputation: 471
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.
Upvotes: 0
Views: 6258
Reputation: 1540
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.
Upvotes: 5
Reputation: 559
This will return the enum string:
enum E : int
{
Element1 = 42
}
//...
int i = 42;
string s = ((E)i).ToString();// returns "Element1"
//...
Upvotes: 0