How can I save an enumeration value to a database?

人盡茶涼 提交于 2020-01-23 09:29:09

问题


For example:

namespace PizzaSoftware.Data
{
    public class User
    {
        public string Username { get; set; }
        public string Password { get; set; }
        public Permission PermissionType { get; set; }
    }

    public enum Permission
    {
        Basic,
        Administrator
    }
}

If if I were to use Entity-Framework's CodeFirst, how can I save this value?

This is for a Windows Forms, Desktop application.

Thank you!


回答1:


You can retrieve the int value (or whatever type you have your enum set to) via a simple cast and save that to the DB.

And to read it back out, you'd cast from int back to enum:

Permission enumValue = (Permission)intValue;



回答2:


You need to understand that an enum is just a set of named constants. Here is a quote from msdn:

The enum keyword is used to declare an enumeration, a distinct type consisting of a set of named constants called the enumerator list. Every enumeration type has an underlying type, which can be any integral type except char. The default underlying type of the enumeration elements is int. By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1.

So to store the value in the database you just store the underlying type and cast/parse as needed.



来源:https://stackoverflow.com/questions/5413803/how-can-i-save-an-enumeration-value-to-a-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!