1

this is how I declare enums:

Enum GROUP_TYPE {
    TYPE1,
    TYPE2
}

this is how I store them:

GroupTypes(id, code) //code is the enum value name
Groups(id, groupName, groupTypeId)

In the InsertGroup stored procedure (I am using stored procedures) I receive @type_code as nvarchar and use it to find the correct id of the group type. I am using this method in order to seperate between the code and the db (the enum number doesn't have to be the same as the id in GroupTypes table).

In the GetGroups stored procedure, in order to read the code from the datatable, I am checking if the type code is defined in GROUP_TYPE and if so I parse the string code to the enum object.

Am I doing things right? Is there any better way to deal with enums in code and db?

2

2 Answers 2

3

I would make the enum and the id in the table be the same.

enum Group
{
  Group1 = 1,
  Group3 = 3
}

This is the easiest and most failsafe way.

Sign up to request clarification or add additional context in comments.

1 Comment

But this makes the code depend on the db in terms of data and not in terms of scheme.
0

I usually map the enum value or name (preferably the explicitly set numeric value as per BryceH) as a database column and add a constraint to the column, making sure to note that in the comment for the enum

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.