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.
I want to save the data as Human and Zombie, not with int.
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.
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.
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.
Enum constants can only be of ordinal types ( int by default), so you can't have string constants in enums.
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With