Sharpeye500
Sharpeye500

Reputation: 9063

Enum class value inside a table

I have an enum class like this:

public enum  MessageType
    {
        ActiveType,
        ErrorType,
        SuccessType
    }

I have a class that has that enum as shown below.

public partial class Message
    {
        public int MessageId { get; set; }
        public MessageType MessageType { get; set; }
        public int Version { get; set; }       
    }

I want to create a sql server table based on the class Message.

Create table Message 
(messageId int,
 Version int)

How do i insert a column for enum entry to create a sql table?

I am creating table based on looking the code.

Upvotes: 3

Views: 1279

Answers (3)

D-Shih
D-Shih

Reputation: 46219

enum is value type so you can do that

public enum  MessageType : int
{
    ActiveType=0,
    ErrorType=1,
    SuccessType=2
}

then create a column messageType int in Message table

Create table Message 
(
  messageId int,
  messageType int,
  Version int
)

You need to convert your MessageType to integer and insert it.

MessageType type= MessageType.ActiveType;
int dbtype = (int)type;

you can insert dbtype to your table

Upvotes: 3

jmcilhinney
jmcilhinney

Reputation: 54417

The point of enums is that they are just numbers under the hood, thus very efficient for the system to work with, but each number corresponds to a text label, thus they are very efficient for human developers to work with. In your case, you're accepting the default numbering, which means that each field is represented by an int and those values are sequential and start at 0. That means that ActiveType, ErrorType and SuccessType correspond to 0, 1 and 2 respectively.

If you want a database column to store that data then you either need a column to store the numeric values or a column to store the text labels. The choice is yours but I would recommend the former. You can cast back and forth between int and MessageType so you simply retrieve the int values from the database and cast as MessageType to load into your Message objects. You can then cast back to int to save.

One result of that is that you will only have numeric values in your database and no text labels. If you want to be able to see what those numbers means when looking at the database directly, you simply add a lookup table that contains the same number-to-text relationships as your enum.

Upvotes: 2

Gaurang Dave
Gaurang Dave

Reputation: 4046

You can create a Master table for your Enum values and then reference primary key to another table.

create table MessageType
(
  MessageTypeId int PRIMARY KEY,
  MessageType varchar(25)
);

create table Message 
(
  MessageId int PRIMARY KEY,
  MessageTypeId int,
  Version int
);

Benefit of creating this is that you can introduce new message type in future if your system extends and it will not create any problem.

Upvotes: 3

Related Questions