Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save enum in database as string

This is my Model Class where we have a Type, which could be a Zombie or Human.

public class User {     public int ID { get; set; }     public string Name { get; set; }     public Type Type { get; set; }     public List<Weapon> WeaponsInList { get; set; } }    public enum Type {        [Description("Zombie")]     Zombie,          [Description("Human")]     Human } 

Currently, it is saving data in Int.

enter image description here

I want to save the data as Human and Zombie, not with int.

like image 742
ZCoder Avatar asked Sep 12 '15 18:09

ZCoder


People also ask

How do I convert an enum to a string?

There are two ways to convert an Enum to String in Java, first by using the name() method of Enum which is an implicit method and available to all Enum, and second by using toString() method.

Can we store enum in database?

First of all, in order to save enum values in a relational database using JPA, you don't have to do anything. By default, when an enum is a part of an entity, JPA maps its values into numbers using the ordinal() method. What it means is that without customizations JPA stores enum value as numbers.

Can we use enum as string?

In a string enum, each member has to be constant-initialized with a string literal, or with another string enum member. While string enums don't have auto-incrementing behavior, string enums have the benefit that they “serialize” well.

Can enum store string?

Enum constants can only be of ordinal types ( int by default), so you can't have string constants in enums.


2 Answers

In Entity Framework Core you can specify the built-in conversion:

modelBuilder     .Entity<DataSet>()     .Property(d => d.SemanticType)     .HasConversion(new EnumToStringConverter<DataSetSemanticType>()); 

More details here.

like image 196
Martin Staufcik Avatar answered Sep 21 '22 19:09

Martin Staufcik


You can save the enum to the db as a string, and I agree with dotctor that it is not the best idea, but if you need to, you need to make a few changes.

public class User {     public int ID { get; set; }     public string Name { get; set; }     public List<Wepon> WeposInList { get; set; }      [Column("Type")]     public string TypeString     {        get { return Type.ToString(); }        private set { Type= value.ParseEnum<Type>(); }     }      [NotMapped]     public Type Type { get; set; } }   

Add this extension class to your project.

public static class StringExtensions {     public static T ParseEnum<T>(this string value)     {         return (T)Enum.Parse(typeof(T), value, true);     } } 

Full details are here - http://NoDogmaBlog.bryanhogan.net/2014/11/saving-enums-as-strings-with-entity-framework/

like image 28
Bryan Avatar answered Sep 19 '22 19:09

Bryan