0

I work with a old database where everything is saved as a string. I have a client table and this table has a status column. I also use entity framework code first. Still version 6. I used reverse engineering system to start a code first from database at beginning.

        [StringLength(1)]
        public string status { get; set; }

What you need to understand is that everything that should be an enum in a good database design is a string in my database. In my C# I would like to use the enum. How can I do to save a enum as a string by default in my database and read is has a string and parse it as a enum?

Bastien Vandamme
  • 17,659
  • 30
  • 118
  • 200
  • 1
    Does this answer your question? [How to save enum in database as string](https://stackoverflow.com/questions/32542356/how-to-save-enum-in-database-as-string) – jalsh Feb 04 '20 at 03:23

1 Answers1

1

Given

public enum MyFunkyEnum
{
   SomeValue
}

You could just use a calculated property that is not in the actual db schema

public string status { get; set; }

public MyFunkyEnum MyFunkyEnumStatus => (MyFunkyEnum)Enum.Parse(typeof(MyFunkyEnum), status);

Note : You will need to use tweak the logic if you have null or empty strings

or both directions

[NotMapped]
public MyFunkyEnum  MyFunkyEnumStatus
{
    get => (MyFunkyEnum) Enum.Parse(typeof(MyFunkyEnum), status);
    set => status = value.ToString();
}
TheGeneral
  • 79,002
  • 9
  • 103
  • 141