public ActionItemWorkflow(Guid instanceId)
 {
     using (WorkflowEntities db = new WorkflowEntities())
     {
         Instance i = db.Instances.Single(x => x.InstanceId == instanceId);
         UnWrap(i.WorkflowData);
     }
 }
 public static bool IsComplete(Guid instanceId)
 {
     using (WorkflowEntities db = new WorkflowEntities())
     {
         Instance i = db.Instances.Single(x => x.InstanceId == instanceId);
         BinaryFormatter bf = new BinaryFormatter();
         using (MemoryStream ms = new MemoryStream())
         {
             ms.Write(i.WorkflowData, 0, i.WorkflowData.Length);
             ms.Seek(0, SeekOrigin.Begin);
             return ((BaseWorkflow)bf.Deserialize(ms)).IsCompleted;
         }
     }
 }
        public Guid CreateInstance(int recordId, int requestedById)
        {
            //set properties
            InstanceId = Guid.NewGuid();
            RecordId = recordId;
            IsCompleted = false;
            setFirstState();
            CurrentState = FirstState;

            //wrap and save
            using (WorkflowEntities db = new WorkflowEntities())
            {
                Instance ins = new Instance()
                {
                    InstanceId = InstanceId,
                    WorkflowData = Wrap()
                };

                History hst = new History()
                {
                    FromState = "",
                    InstanceId = ins.InstanceId,
                    ToState = FirstState.Name,
                    TransitionBy = requestedById,
                    TransitionDate = DateTime.Now
                };

                db.Entry(ins).State = EntityState.Added;
                db.Entry(hst).State = EntityState.Added;
                db.SaveChanges();
                return ins.InstanceId;
            }
        }
        public bool TryAdvance(int requestedBy)
        {
            if (CurrentState.CanProgress())
            {
                string fromState = CurrentState.Name;
                CurrentState = CurrentState.GetNextState();
                IsCompleted = CurrentState.IsFinalState ? true : false;

                History hst = new History()
                {
                    FromState = fromState,
                    ToState = CurrentState.Name,
                    InstanceId = InstanceId,
                    TransitionBy = requestedBy,
                    TransitionDate = DateTime.Now
                };

                using (WorkflowEntities db = new WorkflowEntities())
                {
                    Instance ins = db.Instances.Single(x => x.InstanceId == this.InstanceId);
                    ins.WorkflowData = Wrap();
                    db.Entry(ins).State = EntityState.Modified;
                    db.Entry(hst).State = EntityState.Added;
                    db.SaveChanges();
                }

                return true;
            }
            return false;
        }