0

I have a model with a property of type enum. In the database I want to store not the enum value number and the value itself as a string. And when using EF Core FirstOrDefault I get the value from the database I want to convert the string to an enum. I think it can be done with attributes but I don't understand how to do it. I hope I wrote clearly

public enum MyEnum
{
    value1,
    value2,
    value3
}   

public class MyClass
{
    public int Id;  
    public MyEnum myEnum; //in the database the string "value2". Now of course it's a mistake. Need to convert from string to enum value
}

var myClass = context.MyClases.FirstOrDefault(x => x.Id == Id);
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
kokon231
  • 15
  • 4
  • https://stackoverflow.com/questions/16100/convert-a-string-to-an-enum-in-c-sharp is this helpful? – aca Jul 04 '22 at 07:59
  • Does this answer your question? [Store enum names in database with Entity Framework](https://stackoverflow.com/questions/27509273/store-enum-names-in-database-with-entity-framework) – sschwei1 Jul 04 '22 at 08:06
  • You did not write clearly. "In the database I want to store not the enum value number and the value itself as a string" makes no sense. What do you want to store? – Palle Due Jul 04 '22 at 08:08
  • Please see the duplicate and the [Docs](https://learn.microsoft.com/en-us/ef/core/modeling/value-conversions?tabs=data-annotations#configuring-a-value-converter) – Guru Stron Jul 04 '22 at 08:11

1 Answers1

0

Inside your DbContext override the OnModelCreating and specify the following configuration.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder
        .Entity<MyClass>()
        .Property(e => e.myEnum)
        .HasConversion(
            v => v.ToString(),
            v => (MyEnum)Enum.Parse(typeof(MyEnum), v));
}

or

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder
        .Entity<MyClass>()
        .Property(e => e.myEnum)
        .HaveConversion<StringToEnumConverter<MyEnum>>()
}

This will run a conversation for this property and what's stored in the databsae.

Kevin Smith
  • 13,746
  • 4
  • 52
  • 77