What is a good way to denote "type" in database?
I have a base class Action
which is inherited by numerous child classes. Action
has members like Id
, Name
etc all which corresponds to equivalent columns in a table in the database called action
. So action
table looks like this:
id | name | type
The type
column denotes what action it is. In my code they correspond to the child classes deriving from parent Action
. Now how do I save the type of class to the type field in database?
The type column in db could be of any data type.
Options:
Save
action.GetType().ToString()
as string in db. And get the action type from db back by converting the string representation of the type to its original type using reflection. But this will be problematic if class names change in future.Create an enum to denote each child class and decorate it by a
TypeAttribute
, something like:public abstract class Action { public enum Kind { [Type(typeof(ControlAction))] ControlAction = 1, [Type(typeof(UpdateAction))] UpdateAction = 2, etc } public abstract Kind ActionType { get; } } public class ControlAction : Action { public override Kind ActionType { get { return Kind.ControlAction; } } } public class UpdateAction : Action { public override Kind ActionType { get { return Kind.UpdateAction; } } } //etc
This looks good, except that for each class from here onwards I have to create an enum. And it feels like a little too much work to be done.
Build a separate static hash table of
<int, Type>
that ties a class to aint
value. May be a little bit unreadable.
Is there a better solution to this?