using Enum in database and .net
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 s开发者_JS百科o 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?
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.
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
精彩评论