Agha Agha - 2 months ago 7
C# Question

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<Wepon> WeposInList { 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

Answer

I thing, that it is much more useful to store them as int because you can then cast the int from DB very easily to the enum.

But if it what you desire, there are two approaches. You can save Type.Zombie.ToString() (or Type.Human.ToString() respectively) to database (which will be "Zombie"), or you can obtain the value of DescriptionAttribute, which you are using and save that to the DB. How to get the description is described here. - It will be also "Zombie" in this case, but it may be whatever else you write in the Description().

If you use ToString you can then use Enum.Parse to get the instance of the enum back. If you use the description, it is not that easy.