public ActionResult Index(string userCode)
        {
            var rootNode = new Code();
            rootNode.id = Guid.NewGuid();
            rootNode.userCode = userCode;
            rootNode.version = 0;
            rootNode.CreateDate = DateTime.Now;
            rootNode.latest = false;
            context.Codes.Add(rootNode);

            var editNode = CreateEditNode(rootNode.id, userCode, rootNode, rootNode: true);

            Save();

            return RedirectToAction("Edit", "Home", new { parentId = editNode.parentId, version = editNode.version });
        }
 private Code GetLatestCode(Code currentCodeInView)
 {
     return context.Codes.Single(c => c.parentId == currentCodeInView.parentId && c.latest);
 }
        private int GetLatestVersion(Code currentCodeInView)
        {
            bool isParentCode = currentCodeInView.parentId == null;
            if (isParentCode)
                return 1;

            int newVersion = GetLatestCode(currentCodeInView).version + 1;
            return newVersion;
        }
        private Code CreateEditNode(Guid parentId, string userCode, Code currentCodeInView, bool rootNode = false)
        {
            var editNode = new Code();
            editNode.id = Guid.NewGuid();
            editNode.userCode = userCode;
            if (!rootNode)
            {
                var latestCode = GetLatestCode(currentCodeInView);
                latestCode.latest = false;
            }

            editNode.version = GetLatestVersion(currentCodeInView);
            editNode.CreateDate = DateTime.Now;
            editNode.parentId = parentId;
            editNode.latest = true;

            context.Codes.Add(editNode);

            return editNode;
        }