delete
delete

Reputation:

How can I save an enumeration value to a database?

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!

Upvotes: 3

Views: 3645

Answers (2)

Brent Stewart
Brent Stewart

Reputation: 1840

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.

Upvotes: 0

Kon
Kon

Reputation: 27441

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;

Upvotes: 7

Related Questions