Best way to save type of class in database?

后端 未结 3 965
无人及你
无人及你 2020-12-21 10:53

What is a good way to denote \"type\" in database?

I have a base class Action which is inherited by numerous child classes. Actio

3条回答
  •  [愿得一人]
    2020-12-21 11:30

    I ended up using option 2, but with less clutter of attributes. Something like this:

    public abstract class Action
    {
        public enum Kind 
        {
            ControlAction = 1, 
    
            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; } } }
    

    The biggest advantage for this is that (even if it meant more typing), it enforces a numeric value to be associated with a class type.

    Now class to int is just:

    var value = (int)instance.ActionType;
    

    Very fast.

    But to convert int to class instance (or class type), I will have to create an instance of each sub action types, and compare its ActionType property to match the input int value. This is going to be slow. But I can cache somethings and make it faster. Something like:

    static readonly Dictionary actionTypes = 
       GetDefaultInstanceOfAllActions().ToDictionary(x => x.ActionType, x => x.GetType());
    public static Action ToAction(this Action.Kind value)
    {
        return (Action)Activator.CreateInstance(actionTypes[value]);
    }
    

    The GetDefaultInstanceOfAllActions does some reflection (once) to get all types of actions (I use something like this answer for that). I can even make the make the instantiation faster by going the expression route.

    The benefits:

    1. Less hassle when creating a new class (no attributes).

    2. Enforces an int to be tied to a class type.

    3. Moderately fast with adequate caching.

提交回复
热议问题