Persisting the state pattern using Entity Framework

I think you can improve it by caching the State instances creating it only once, to avoid making the list each time and avoid the foreach:

public static class StateFactory
{
    private static Dictionary<string, State> statesCache = FindAllDerivedStates();

    public static State GetState(string stateTypeName)
    {
        return statesCache[stateTypeName];
    }

    private static Dictionary<string, State> FindAllDerivedStates()
    {
        var derivedType = typeof(State);
        var assembly = Assembly.GetAssembly(typeof(State));
        return assembly.GetTypes().Where(t => t != derivedType && derivedType.IsAssignableFrom(t))
                    .Select(t => (State)Activator.CreateInstance(t))
                    .ToDictionary(k => k.Name);
    }
}

I've made some progress by simplifying the factory back to basics and by implementing it in such a way that you would never really know that a factory is being used. Although It's not what I was looking for, it is so refined and streamlined the only downside is I still don't have a list of ALL states within the SQL database, there are however many possible work arounds for this. Anyway... my compromise:

The State Factory:

public static State GetState(string stateTypeName)
{
    var list = FindAllDerivedStates();
    dynamic returnedValue = new NullState();
    foreach(var state in list)
    {
        if(state.Name == stateTypeName) returnedValue = (State)Activator.CreateInstance(state);
    }
    return returnedValue
}

private static List<Type> FindAllDerivedStates()
{
    var derivedType = typeof(State);
    var assembly = Assembly.GetAssembly(typeof(State));
    return assembly.GetTypes().Where(t => t != derivedType && derivedType.IsAssignableFrom(t)).ToList();
}

Now the request needs two properties, a persisted string and a State class. Make sure the State class is not mapped.

public class Request
{
    public string StateString { get; set; }

    [NotMapped] or [Ignore]
    public State CurrentState 
    { 
        get
        {
            return StateFactory.GetState(this.StateString); 
        }
        set
        { 
            this.State = value.GetType().Name; 
        }
    }
}

Now because of the new simplistic implementation, saving the state is as easy as;

request.CurrentState = new OpenState();

and getting the state will always return the methods. Without any extra work you can return an entity and excess the properties. For example if you want output the public string;

request.CurrentState.StateName;

Now I've still got to implement a little work around to add a list of states to my SqlDb but that's not the end of the world. It seems this is the only solution. Or should I say best solution. I'll keep my eyes peeled for a better version.