Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 484
Sharpeye500 Avatar asked Apr 22 '26 16:04

Sharpeye500


2 Answers

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.

like image 193
Gaurang Dave Avatar answered Apr 25 '26 05:04

Gaurang Dave


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

like image 34
D-Shih Avatar answered Apr 25 '26 06:04

D-Shih