public async Task <JsonResult> SaveAsync(MarketHierarchyViewModel record)
        {
            try
            {
                MarketHierarchy mh = null;

                if (ModelState.IsValid)
                {
                    MarketHierarchyModel model = new MarketHierarchyModel(_unitOfWork);
                    mh = await model.SaveAsync(record);

                    logger.Debug("Market Hierarchy saved successfully.");

                    return(Json(new MarketHierarchyTreeViewModel()
                    {
                        text = mh.Code + "-" + mh.Name, code = mh.Code, id = mh.Id, name = mh.Name, parentId = mh.ParentId != null?mh.ParentId.Value:-1, type = mh.Type.ToString()
                    }, JsonRequestBehavior.AllowGet));
                }
                else
                {
                    return(Json(new { result = false }, JsonRequestBehavior.AllowGet));
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error while invoking Save action method: ", ex);
                return(Json(new { result = false, error = ex.Message }, JsonRequestBehavior.AllowGet));
            }
        }
        public async Task <MarketHierarchy> SaveAsync(MarketHierarchyViewModel record)
        {
            MarketHierarchy mh     = null;
            MarketHierarchy parent = null;

            if (record.Id != null)
            {
                mh = _unitOfWork.MarketHierarchies.Get(record.Id.Value);
                if (mh == null)
                {
                    throw new Exception("Invalid Market Hierarchy Id");
                }

                mh.UpdatedBy   = System.Web.HttpContext.Current.User.Identity.Name;
                mh.UpdatedDate = DateTime.Now;
            }
            else
            {
                mh = new MarketHierarchy();
                _unitOfWork.MarketHierarchies.Add(mh);

                mh.CreatedBy = System.Web.HttpContext.Current.User.Identity.Name;
            }

            if (record.ParentId != null)
            {
                parent = _unitOfWork.MarketHierarchies.Get(record.ParentId.Value);
            }

            mh.Code   = record.Code;
            mh.Name   = record.Name;
            mh.Parent = parent;
            mh.Type   = parent != null ? parent.Type + 1 : MarketHierarchyType.Nation;

            await _unitOfWork.CompleteAsync();

            return(mh);
        }