How to save enum in database as string

后端 未结 6 687
北恋
北恋 2020-12-29 02:59

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 { ge         


        
6条回答
  •  执念已碎
    2020-12-29 03:39

    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.

提交回复
热议问题