private static List<LABStudyOptionValue> GetOptionValueList(Guid idLABStudy, LABStudyOptionValue optionValueRoot)
        {
            using (UpsilabEntities context = new UpsilabEntities())
            {
                var query = from optionValue in context.LABStudyOptionValue.Include("LABStudyOptionAttributeValue")
                            join option in context.Option on optionValue.idOption equals option.idOption
                            where optionValue.idLABStudy.Equals(idLABStudy)
                            where option.idParent.Value.Equals(optionValueRoot.idOption)
                            select optionValue;

                List<Data.Model.LABStudyOptionValue> returnValue = new List<LABStudyOptionValue>();
                foreach (var optionValue in query.ToList())
                {
                    context.LoadProperty(optionValue, "LABStudyOptionAttributeValue");
                    returnValue.Add(optionValue);
                    returnValue.AddRange(GetOptionValueList(idLABStudy, optionValue));
                }

                return returnValue;
            }
        }
        public static void FindAndReplaceValue(LABStudyOptionValue optionValue, List<int> idOptionAttributes, List<String> values)
        {
            if (idOptionAttributes.Count != values.Count)
                throw new Exception("Invalid override count");

            for (int counter = 0; counter <= idOptionAttributes.Count - 1; counter++)
            {
                var item = optionValue.LABStudyOptionAttributeValue.Where(optValAttr => optValAttr.idOptionAttribute == idOptionAttributes[counter]).FirstOrDefault();

                if (item != null)
                {
                    string sValue = values[counter];
                    if (string.IsNullOrEmpty(values[counter]))
                    {
                        sValue = "";
                    }
                    item.Value = sValue;
                }
                else
                {
                    string sValue = values[counter];
                    if (string.IsNullOrEmpty(values[counter]))
                    {
                        sValue = "";
                    }
                    optionValue.LABStudyOptionAttributeValue.Add(new LABStudyOptionAttributeValue() { Value = sValue, idOptionAttribute = idOptionAttributes[counter], idLABStudyOptionValue = optionValue.idLABStudyOptionValue });
                }
            }
        }
        public List<LABStudyOptionValue> GetSelectedOptionsFromPostData(LABStudyModel _dataModel, int idParent)
        {
            CustomerProspect currentCustomer = CustomerProspectBL.GetCustomerProspectById(_dataModel.idCustomer);
            List<LABStudyOptionValue> retVal = new List<LABStudyOptionValue>();

            // idOption = 717 (LabStudy/QuestionClient)
            Option ParentOption = _dataModel.Option.Where(o => o.idOption.Equals(idParent)).FirstOrDefault();

            if (ParentOption != null)
            {
                // => Identité - Forme Juridique - Société cotée - Secteur d’activité
                // => idOption = 718 - 719 - 746 - 750
                var ChildOptions = _dataModel.Option.Where(o => o.idParent.HasValue && o.idParent.Value.Equals(ParentOption.idOption));
                foreach (var childOp in ChildOptions)
                {
                    if (childOp.idParent == 725)
                    { }

                    bool isSelected = !ParentOption.SingleOption.HasValue;
                    string idPrefix = string.Empty;
                    if (ParentOption.SingleOption.HasValue)
                    {
                        if (ParentOption.SingleOption.Value) idPrefix = "hdn_rb_{0}_{1}";
                        else idPrefix = "hdn_chk_{0}_{1}";

                        string postDataName = string.Format(idPrefix, childOp.idParent.Value, childOp.idOption);
                        if (!string.IsNullOrEmpty(Request.Params[postDataName]) && Request.Params[postDataName].ToLower().Equals("c"))
                        {
                            isSelected = true;
                        }
                    }

                    if (isSelected)
                    {
                        LABStudyOptionValue newVal = new LABStudyOptionValue();
                        newVal.idLABStudy = _dataModel.LABStudy.idLABStudy;
                        newVal.idOption = childOp.idOption;
                        newVal.Option = childOp;
                        retVal.Add(newVal);

                        if (_dataModel.Option.Count(o => o.idParent.HasValue && o.idParent.Value.Equals(childOp.idOption)) > 0)
                        {
                            retVal.AddRange(GetSelectedOptionsFromPostData(_dataModel, childOp.idOption));

                            #region Mise à jour du CustomerProspec
                            if (childOp.idParent.Value == 702)
                            {
                                switch (childOp.idOption)
                                {
                                    case (int)NUMOPTIONATTRIBUTE_IDENTITE.ISMAJOR1: currentCustomer.LegalCapacity = "Majeur capable"; break;
                                    case (int)NUMOPTIONATTRIBUTE_IDENTITE.ISMAJOR2: currentCustomer.LegalCapacity = "Majeur sous tutelle"; break;
                                    case (int)NUMOPTIONATTRIBUTE_IDENTITE.ISMAJOR3: currentCustomer.LegalCapacity = "Majeur sous curatelle"; break;
                                    case (int)NUMOPTIONATTRIBUTE_IDENTITE.ISMAJOR4: currentCustomer.LegalCapacity = "Majeur sous sauvegarde de justice"; break;
                                    case (int)NUMOPTIONATTRIBUTE_IDENTITE.ISMAJOR6: currentCustomer.LegalCapacity = "Mineur émancipé"; break;
                                }

                                if (childOp.NameKey.CompareTo("LABPP_Client_032") == 0)
                                    currentCustomer.LegalCapacity = "Mineur non émancipé";
                            }
                            else if (childOp.idParent.Value == 707)
                            {
                                switch (childOp.idOption)
                                {
                                    case (int)NUMOPTIONATTRIBUTE_IDENTITE.ISRESIDENT: currentCustomer.IsResident = isSelected; break;
                                }
                            }
                            else if (childOp.idParent.Value == 711)
                            {
                                switch (childOp.idOption)
                                {
                                    case (int)NUMOPTIONATTRIBUTE_IDENTITE.GAFI: currentCustomer.Gafi = isSelected; break;
                                }
                            }
                            else if (childOp.idParent.Value == 714)
                            {
                                switch (childOp.idOption)
                                {
                                    case (int)NUMOPTIONATTRIBUTE_IDENTITE.OFFSHORE: currentCustomer.OffShore = isSelected; break;
                                }
                            }
                            #endregion
                        }
                    }
                }
            }

            CustomerProspectBL.Update(currentCustomer);

            return retVal;
        }
        public List<LABStudyOptionValue> GetSelectedOptions(LABStudyModel _dataModel)
        {
            List<LABStudyOptionValue> retVal = new List<LABStudyOptionValue>();

            var ParentOptions = _dataModel.Option.Where(o => !o.idParent.HasValue);
            if (ParentOptions != null)
            {
                foreach (var parent in ParentOptions)
                {
                    LABStudyOptionValue _parent = new LABStudyOptionValue();
                    _parent.idLABStudy = _dataModel.LABStudy.idLABStudy;
                    _parent.idOption = parent.idOption;
                    _parent.Option = parent;
                    retVal.Add(_parent);

                    var selectedChild = GetSelectedOptionsFromPostData(_dataModel, parent.idOption);
                    if (selectedChild.Count > 0)
                    {
                        LABStudyOptionValue newVal = new LABStudyOptionValue();
                        newVal.idLABStudy = _dataModel.LABStudy.idLABStudy;
                        newVal.idOption = parent.idOption;
                        newVal.Option = parent;
                        retVal.Add(newVal);
                        retVal.AddRange(selectedChild);
                    }
                }
            }

            return retVal;
        }
        public static List<LABStudyOptionValue> GetParentOptionToAdd(Guid idLABStudy, List<LABStudyOptionValue> lstOptionValues, Data.Model.Option option)
        {
            List<LABStudyOptionValue> lstParentOptionValues = new List<LABStudyOptionValue>();

            using (UpsilabEntities db = new UpsilabEntities())
            {
                //Insert parent ??
                while (option.idParent.HasValue)
                {
                    LABStudyOptionValue optionParentValue = (from lov in lstOptionValues
                                                           where lov.idOption == option.idParent
                                                           select lov).FirstOrDefault();

                    if (optionParentValue == null)
                    {
                        optionParentValue = new LABStudyOptionValue()
                        {
                            idLABStudy = idLABStudy,
                            idOption = option.idParent.Value,
                            Value = string.Empty,
                            DateCreated = DateTime.Now
                        };

                        lstParentOptionValues.Add(optionParentValue);

                        //Check if this parent option has already parent ?
                        option = OptionBL.GetOptionById(optionParentValue.idOption);
                    }
                    else
                    {
                        break;
                    }
                }
            }

            return lstParentOptionValues;
        }
        public static bool UpdateLABStudyOptions(Guid idLABStudy, List<LABStudyOptionValue> SelectedOptions)
        {
            bool retVal = true;
            try
            {
                var parentOptions = SelectedOptions.Where(so => so.Option.idParent.HasValue.Equals(false));
                foreach (var parentOption in parentOptions)
                {

                    List<Data.Model.Option> optList = OptionBL.GetOptionsByIdParent(parentOption.idOption);

                    #region Delete existing OptionAttributeValue under Parent
                    List<LABStudyOptionAttributeValue> toBeDeletedAttr = new List<LABStudyOptionAttributeValue>();
                    using (UpsilabEntities retrieveContext = new UpsilabEntities())
                    {
                        foreach (var opt in optList)
                        {
                            var deleteAttr = (from toBeDel in retrieveContext.LABStudyOptionAttributeValue.ToList()
                                              join o in opt.OptionAttribute on toBeDel.idOptionAttribute equals o.idOptionAttribute
                                              where toBeDel.idLABStudy.Equals(idLABStudy)
                                              select toBeDel).ToList();
                            toBeDeletedAttr.AddRange(deleteAttr);
                        }

                        foreach (var toBeDel in toBeDeletedAttr)
                        {
                            retrieveContext.LABStudyOptionAttributeValue.DeleteObject(toBeDel);
                            retrieveContext.SaveChanges();
                        }
                    }
                    #endregion

                    #region Update OptionValue
                    //Delete existing OptionValue under Parent
                    List<LABStudyOptionValue> toBeDeletedOpt = new List<LABStudyOptionValue>();
                    using (UpsilabEntities retrieveContext = new UpsilabEntities())
                    {
                        toBeDeletedOpt = (from toBeDel in retrieveContext.LABStudyOptionValue.ToList()
                                          join opt in optList on toBeDel.idOption equals opt.idOption
                                          where toBeDel.idLABStudy.Equals(idLABStudy)
                                          select toBeDel).ToList();

                        foreach (var toBeDel in toBeDeletedOpt)
                        {
                            retrieveContext.LABStudyOptionValue.DeleteObject(toBeDel);
                            retrieveContext.SaveChanges();
                        }
                    }
                }

                //Insert new OptionValue
                using (UpsilabEntities insertContext = new UpsilabEntities())
                {
                    foreach (var toBeAdded in SelectedOptions)
                    {
                        LABStudyOptionValue newVal = new LABStudyOptionValue();
                        newVal.idLABStudy = idLABStudy;
                        newVal.idOption = toBeAdded.idOption;
                        newVal.Value = string.Empty;

                        insertContext.LABStudyOptionValue.AddObject(newVal);
                        insertContext.SaveChanges();

                        if (toBeAdded.LABStudyOptionAttributeValue.Count > 0)
                        {
                            foreach (var optAttr in toBeAdded.LABStudyOptionAttributeValue)
                            {
                                LABStudyOptionAttributeValue newAttVal = new LABStudyOptionAttributeValue();
                                newAttVal.idLABStudy = idLABStudy;
                                newAttVal.idOptionAttribute = optAttr.idOptionAttribute;
                                newAttVal.idLABStudyOptionValue = newVal.idLABStudyOptionValue;
                                newAttVal.Value = optAttr.Value;

                                insertContext.LABStudyOptionAttributeValue.AddObject(newAttVal);
                                insertContext.SaveChanges();
                            }
                        }
                    }
                }
                    #endregion
            }
            catch (Exception e)
            {
                retVal = false;
                Log.Log.AppendException(e);
            }
            return retVal;
        }
        private static void SetOptionToSave(Guid idLABStudy, Upsilab.Data.Model.Option option, OptionAttribute optionAttribute, string value, string fieldType, List<LABStudyOptionValue> lstOptionValues, UpsilabEntities db)
        {
            if (option == null && optionAttribute == null)
            {
                return; //ce cas ne doit pas se présenter
            }

            string action = string.Empty;

            LABStudyOptionValue optionValue = null;
            LABStudyOptionAttributeValue optionAttributeValue = null;

            //1- Champ
            #region TXT
            if (fieldType == "txt")
            {
                //Do nothing if value is null. Don't check empty because it's a value :) ?
                if (value == null)
                {
                    return;
                }

                optionValue = lstOptionValues.Where(lov => lov.idOption == optionAttribute.idOption).FirstOrDefault();

                if (optionValue == null)
                {
                    action = "I";
                }
                else
                {
                    optionAttributeValue = optionValue.LABStudyOptionAttributeValue.Where(roav => roav.idOptionAttribute == optionAttribute.idOptionAttribute).FirstOrDefault();
                    if (optionAttributeValue == null)
                    {
                        action = "I";
                    }
                    else
                    {
                        //No need to update if the same value
                        if (optionAttributeValue.Value != value)
                        {
                            optionAttributeValue.Value = value;
                            //optionAttributeValue.DateUpdated = DateTime.Now; TODO
                        }
                    }
                }

                if (action == "I")
                {
                    //Check if LABStudyOptionValue exists
                    if (optionValue == null) //insert option value
                    {
                        optionValue = new LABStudyOptionValue()
                        {
                            idLABStudy = idLABStudy,
                            idOption = option.idOption,
                            Value = string.Empty,
                            DateCreated = DateTime.Now
                        };

                        //Add LABStudyOptionValue to DB : don't save yet
                        lstOptionValues.Add(optionValue);

                        db.LABStudyOptionValue.Attach(optionValue);
                        db.ObjectStateManager.ChangeObjectState(optionValue, System.Data.EntityState.Added);

                        //Insert parent ??
                        List<LABStudyOptionValue> lstParents = GetParentOptionToAdd(idLABStudy, lstOptionValues, option);
                        foreach (var optionParentValue in lstParents)
                        {
                            lstOptionValues.Add(optionParentValue);

                            db.LABStudyOptionValue.AddObject(optionParentValue);
                        }
                    }

                    //Insert optionattrubutevalue
                    LABStudyOptionAttributeValue newLABStudyOptionAttributeValue = new LABStudyOptionAttributeValue()
                    {
                        idLABStudy = idLABStudy,
                        idOptionAttribute = optionAttribute.idOptionAttribute,
                        idLABStudyOptionValue = optionValue.idLABStudyOptionValue,
                        Value = value,
                        DateCreated = DateTime.Now
                    };

                    //Add LABStudyOptionAttributeValue to DB : don't save yet
                    optionValue.LABStudyOptionAttributeValue.Add(newLABStudyOptionAttributeValue);
                }
            }
            #endregion

            //2- Radio
            #region RB
            //2- Save option attribute value (Radio button)
            else if (fieldType == "rb")
            {
                //No need to delete if it's the option
                optionValue = lstOptionValues.Where(lov => lov.idOption == option.idOption).FirstOrDefault();
                if (optionValue == null)
                {
                    //Delete old rb
                    IList<LABStudyOptionValue> optionValues = (from lov in lstOptionValues
                                                             where lov.Option.idParent == option.idParent
                                                             select lov).ToList();

                    //Delete option attribute values attached to option value
                    if (optionValues != null)
                    {
                        foreach (var itemOptionValue in optionValues)
                        {
                            IList<LABStudyOptionAttributeValue> lstOptionAttributeValues = new List<LABStudyOptionAttributeValue>(itemOptionValue.LABStudyOptionAttributeValue);
                            foreach (var item in lstOptionAttributeValues)
                            {
                                var optionAttrValueToBeDel = itemOptionValue.LABStudyOptionAttributeValue.Where(oa => oa.idLABStudyOptionAttributeValue == item.idLABStudyOptionAttributeValue).FirstOrDefault();

                                db.LABStudyOptionAttributeValue.DeleteObject(optionAttrValueToBeDel);
                            }

                            lstOptionValues.Remove(itemOptionValue);

                            db.LABStudyOptionValue.DeleteObject(itemOptionValue);

                            //Delete child option value
                            IList<LABStudyOptionValue> lstOptionValuesChild = (from lov in lstOptionValues
                                                                             where lov.Option.idParent == itemOptionValue.idOption
                                                                             select lov).ToList();

                            if (lstOptionValuesChild != null)
                            {
                                foreach (var optionValueChild in lstOptionValuesChild)
                                {
                                    lstOptionAttributeValues = new List<LABStudyOptionAttributeValue>(optionValueChild.LABStudyOptionAttributeValue);
                                    foreach (var item in lstOptionAttributeValues)
                                    {
                                        var optionAttrValueToBeDel = optionValueChild.LABStudyOptionAttributeValue.Where(oa => oa.idLABStudyOptionAttributeValue == item.idLABStudyOptionAttributeValue).FirstOrDefault();

                                        db.LABStudyOptionAttributeValue.DeleteObject(optionAttrValueToBeDel);
                                    }

                                    lstOptionValues.Remove(optionValueChild);

                                    db.LABStudyOptionValue.DeleteObject(optionValueChild);
                                }
                            }
                        }

                    }

                    //Insert new rb
                    LABStudyOptionValue newOptionValue = new LABStudyOptionValue()
                    {
                        idLABStudy = idLABStudy,
                        idOption = option.idOption,
                        Value = string.Empty,
                    };

                    //Add LABStudyOptionValue to DB : don't save yet
                    lstOptionValues.Add(newOptionValue);

                    db.LABStudyOptionValue.AddObject(newOptionValue);

                    //Insert parent
                    List<LABStudyOptionValue> lstParents = GetParentOptionToAdd(idLABStudy, lstOptionValues, option);
                    foreach (var optionParentValue in lstParents)
                    {
                        lstOptionValues.Add(optionParentValue);

                        db.LABStudyOptionValue.AddObject(optionParentValue);
                    }
                }
            }
            #endregion

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="idLabStudy"></param>
        /// <param name="option"></param>
        /// <param name="idOptionAttribute"></param>
        /// <param name="value"></param>
        /// <param name="fieldType"></param>
        public static void SaveLabStudyOptionValue(Guid idLabStudy, Upsilab.Data.Model.Option option, int idOptionAttribute, string value, string fieldType)
        {
            int idOption = option.idOption;
            bool hasSentToCoffreLAB = false;
            string sentToCoffreStatus = LABStudy.StatusEnum.SentToCoffreFort.ToString();

            //Insert new OptionValue
            using (UpsilabEntities db = new UpsilabEntities())
            {
                //Get current report
                Data.Model.LABStudy labStudy = (from lab in db.LABStudy
                                                where lab.idLABStudy == idLabStudy
                                                select lab).FirstOrDefault();

                //Check if customer has "SentToCoffreFort" LAB
                var checkSentToCoffreLAB = (from lab in db.LABStudy
                                            where lab.CustomerProspect.idCustomer == labStudy.CustomerProspect.idCustomer
                                                  && lab.Status == sentToCoffreStatus
                                            select lab).FirstOrDefault();

                if (checkSentToCoffreLAB != null)
                {
                    hasSentToCoffreLAB = true;
                }

                #region TEXTBOX, DROPDOWN : txt, dt, enum
                //1- Save option attribute value (simple textbox / textarea)
                if (fieldType == "otxt" || fieldType == "dt" || fieldType == "enum")
                {
                    LABStudyOptionAttributeValue optionAttributeValue = (from laboav in db.LABStudyOptionAttributeValue.Include("LABStudyOptionValue")
                                                                       where laboav.idLABStudy == idLabStudy && laboav.idOptionAttribute == idOptionAttribute
                                                                       select laboav).FirstOrDefault();

                    if (optionAttributeValue != null)
                    {
                        if (optionAttributeValue.Value != value) //update if not equal
                        {
                            optionAttributeValue.Value = value;
                            optionAttributeValue.DateUpdated = (hasSentToCoffreLAB) ? DateTime.Now : (DateTime?)null;
                        }
                        else
                        { 
                            //Do nothing if equal
                        }
                    }
                    else if (!string.IsNullOrEmpty(value)) //Insert if value is not empty
                    {
                        //Check if LABStudyOptionValue exists
                        LABStudyOptionValue optionValue = (from lov in db.LABStudyOptionValue
                                                            where lov.idLABStudy == idLabStudy && lov.idOption == idOption
                                                            select lov).FirstOrDefault();

                        if (optionValue == null) //insert option value
                        {
                            optionValue = new LABStudyOptionValue()
                            {
                                idLABStudy = idLabStudy,
                                idOption = idOption,
                                Value = string.Empty,
                                DateCreated = DateTime.Now,
                                DateUpdated = (hasSentToCoffreLAB) ? DateTime.Now : (DateTime?)null
                            };

                            //Add LABStudyOptionValue to DB : don't save yet
                            db.LABStudyOptionValue.AddObject(optionValue);

                            //Insert parent ??
                            while (option.idParent.HasValue)
                            {
                                LABStudyOptionValue optionParentValue = (from lov in db.LABStudyOptionValue.Include("Option")
                                                                       where lov.idLABStudy == idLabStudy && lov.idOption == option.idParent
                                                                       select lov).FirstOrDefault();

                                if (optionParentValue == null)
                                {
                                    optionParentValue = new LABStudyOptionValue()
                                    {
                                        idLABStudy = idLabStudy,
                                        idOption = option.idParent.Value,
                                        Value = string.Empty,
                                        DateCreated = DateTime.Now,
                                        DateUpdated = (hasSentToCoffreLAB) ? DateTime.Now : (DateTime?)null
                                    };

                                    //Add LABStudyOptionValue to DB : don't save yet
                                    db.LABStudyOptionValue.AddObject(optionParentValue);

                                    //Check if this parent option has already parent ?
                                    option = optionParentValue.Option;
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }

                        //Insert optionattrubutevalue
                        LABStudyOptionAttributeValue newLABStudyOptionAttributeValue = new LABStudyOptionAttributeValue()
                        {
                            idLABStudy = idLabStudy,
                            idOptionAttribute = idOptionAttribute,
                            idLABStudyOptionValue = optionValue.idLABStudyOptionValue,
                            Value = value,
                            DateCreated = DateTime.Now,
                            DateUpdated = (hasSentToCoffreLAB) ? DateTime.Now : (DateTime?)null
                        };

                        //Add LABStudyOptionAttributeValue to DB : don't save yet
                        optionValue.LABStudyOptionAttributeValue.Add(newLABStudyOptionAttributeValue);
                    }
                }
                #endregion

                #region RADIO BUTTON : rb
                //2- Save option attribute value (Radio button)
                else if (fieldType == "rb")
                {
                    //Delete old rb
                    IList<LABStudyOptionValue> optionValues = (from lov in db.LABStudyOptionValue.Include("LABStudyOptionAttributeValue")
                                                             where lov.idLABStudy == idLabStudy && lov.Option.idParent == option.idParent
                                                             select lov).ToList();

                    //Delete option attribute values attached to option value
                    if (optionValues != null)
                    {
                        foreach (var optionValue in optionValues)
                        {
                            IList<LABStudyOptionAttributeValue> lstOptionAttributeValues = new List<LABStudyOptionAttributeValue>(optionValue.LABStudyOptionAttributeValue);
                            foreach (var item in lstOptionAttributeValues)
                            {
                                var optionAttrValueToBeDel = optionValue.LABStudyOptionAttributeValue.Where(oa => oa.idLABStudyOptionAttributeValue == item.idLABStudyOptionAttributeValue).FirstOrDefault();
                                db.LABStudyOptionAttributeValue.DeleteObject(optionAttrValueToBeDel);
                            }

                            db.LABStudyOptionValue.DeleteObject(optionValue);

                            //Delete child option value
                            IList<LABStudyOptionValue> lstOptionValuesChild = (from lov in db.LABStudyOptionValue.Include("LABStudyOptionAttributeValue")
                                                                             where lov.idLABStudy == idLabStudy && lov.Option.idParent == optionValue.idOption
                                                                             select lov).ToList();

                            if (lstOptionValuesChild != null)
                            {
                                foreach (var optionValueChild in lstOptionValuesChild)
                                {
                                    lstOptionAttributeValues = new List<LABStudyOptionAttributeValue>(optionValueChild.LABStudyOptionAttributeValue);
                                    foreach (var item in lstOptionAttributeValues)
                                    {
                                        var optionAttrValueToBeDel = optionValueChild.LABStudyOptionAttributeValue.Where(oa => oa.idLABStudyOptionAttributeValue == item.idLABStudyOptionAttributeValue).FirstOrDefault();
                                        db.LABStudyOptionAttributeValue.DeleteObject(optionAttrValueToBeDel);
                                    }

                                    db.LABStudyOptionValue.DeleteObject(optionValueChild);
                                }
                            }
                        }

                    }

                    //Insert new rb
                    LABStudyOptionValue newOptionValue = new LABStudyOptionValue()
                    {
                        idLABStudy = idLabStudy,
                        idOption = idOption,
                        Value = string.Empty,
                        DateCreated = DateTime.Now,
                        DateUpdated = (hasSentToCoffreLAB) ? DateTime.Now : (DateTime?)null
                    };

                    //Add LABStudyOptionValue to DB : don't save yet
                    db.LABStudyOptionValue.AddObject(newOptionValue);

                    //Insert parent ??
                    while (option.idParent.HasValue)
                    {
                        LABStudyOptionValue optionParentValue = (from lov in db.LABStudyOptionValue.Include("Option")
                                                               where lov.idLABStudy == idLabStudy && lov.idOption == option.idParent
                                                               select lov).FirstOrDefault();

                        if (optionParentValue == null)
                        {
                            optionParentValue = new LABStudyOptionValue()
                            {
                                idLABStudy = idLabStudy,
                                idOption = option.idParent.Value,
                                Value = string.Empty,
                                DateCreated = DateTime.Now,
                                DateUpdated = (hasSentToCoffreLAB) ? DateTime.Now : (DateTime?)null
                            };

                            //Add LABStudyOptionValue to DB : don't save yet
                            db.LABStudyOptionValue.AddObject(optionParentValue);

                            //Check if this parent option has already parent ?
                            option = optionParentValue.Option;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                #endregion

                #region CHECKBOX : chk
                //3- Save option attribute value (Checkbox)
                else if (fieldType == "chk")
                {
                    LABStudyOptionValue optionValue;

                    if (value == "false")
                    {
                        //Delete old chk
                        optionValue = (from lov in db.LABStudyOptionValue.Include("LABStudyOptionAttributeValue")
                                       where lov.idLABStudy == idLabStudy && lov.idOption == idOption
                                       select lov).FirstOrDefault();

                        //Delete option attribute values attached to option value
                        if (optionValue != null)
                        {
                            IList<LABStudyOptionAttributeValue> lstOptionAttributeValues = new List<LABStudyOptionAttributeValue>(optionValue.LABStudyOptionAttributeValue);
                            foreach (var item in lstOptionAttributeValues)
                            {
                                var optionAttrValueToBeDel = optionValue.LABStudyOptionAttributeValue.Where(oa => oa.idLABStudyOptionAttributeValue == item.idLABStudyOptionAttributeValue).FirstOrDefault();
                                db.LABStudyOptionAttributeValue.DeleteObject(optionAttrValueToBeDel);
                            }

                            db.LABStudyOptionValue.DeleteObject(optionValue);

                            //Delete child option value
                            IList<LABStudyOptionValue> lstOptionValuesChild = (from lov in db.LABStudyOptionValue.Include("LABStudyOptionAttributeValue")
                                                                             where lov.idLABStudy == idLabStudy && lov.Option.idParent == optionValue.idOption
                                                                             select lov).ToList();

                            if (lstOptionValuesChild != null)
                            {
                                foreach (var optionValueChild in lstOptionValuesChild)
                                {
                                    lstOptionAttributeValues = new List<LABStudyOptionAttributeValue>(optionValueChild.LABStudyOptionAttributeValue);
                                    foreach (var item in lstOptionAttributeValues)
                                    {
                                        var optionAttrValueToBeDel = optionValueChild.LABStudyOptionAttributeValue.Where(oa => oa.idLABStudyOptionAttributeValue == item.idLABStudyOptionAttributeValue).FirstOrDefault();
                                        db.LABStudyOptionAttributeValue.DeleteObject(optionAttrValueToBeDel);
                                    }

                                    db.LABStudyOptionValue.DeleteObject(optionValueChild);
                                }
                            }
                        }
                    }
                    else if (value == "true")
                    {
                        //Insert new chk
                        optionValue = new LABStudyOptionValue()
                        {
                            idLABStudy = idLabStudy,
                            idOption = idOption,
                            Value = string.Empty,
                            DateCreated = DateTime.Now,
                            DateUpdated = (hasSentToCoffreLAB) ? DateTime.Now : (DateTime?)null
                        };

                        //Add LABStudyOptionValue to DB : don't save yet
                        db.LABStudyOptionValue.AddObject(optionValue);

                        //Insert parent ??
                        while (option.idParent.HasValue)
                        {
                            LABStudyOptionValue optionParentValue = (from lov in db.LABStudyOptionValue.Include("Option")
                                                                   where lov.idLABStudy == idLabStudy && lov.idOption == option.idParent
                                                                   select lov).FirstOrDefault();

                            if (optionParentValue == null)
                            {
                                optionParentValue = new LABStudyOptionValue()
                                {
                                    idLABStudy = idLabStudy,
                                    idOption = option.idParent.Value,
                                    Value = string.Empty,
                                    DateCreated = DateTime.Now,
                                    DateUpdated = (hasSentToCoffreLAB) ? DateTime.Now : (DateTime?)null
                                };

                                //Add LABStudyOptionValue to DB : don't save yet
                                db.LABStudyOptionValue.AddObject(optionParentValue);

                                //Check if this parent option has already parent ?
                                option = optionParentValue.Option;
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }
                #endregion
              
                //6- Commit all changes here
                db.SaveChanges();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="labStudyIdDest"></param>
        /// <param name="lstLabStudyOptionValuesSource"></param>
        public static void SaveLabStudyOptionValues(Upsilab.Data.Model.LABStudy labStudyDest, List<LABStudyOptionValue> lstLabStudyOptionValuesSource)
        {
            //Insert new OptionValue
            using (UpsilabEntities db = new UpsilabEntities())
            {
                foreach (var labStudyOptionValueSource in lstLabStudyOptionValuesSource)
                {
                    //1- LabStudy option value
                    LABStudyOptionValue newLabStudyOptionValue = new LABStudyOptionValue()
                    {
                        idLABStudy = labStudyDest.idLABStudy,
                        idOption = labStudyOptionValueSource.idOption,
                        Value = string.Empty,
                        DateCreated = DateTime.Now
                    };

                    //Add LabStudyOptionValue to DB : don't save yet
                    db.LABStudyOptionValue.AddObject(newLabStudyOptionValue);

                    if (labStudyOptionValueSource.LABStudyOptionAttributeValue.Count > 0)
                    {
                        //2- LabStudy option attribute value
                        foreach (var labStudyOptAttrValueSource in labStudyOptionValueSource.LABStudyOptionAttributeValue)
                        {
                            LABStudyOptionAttributeValue newLabStudyOptionAttrValue = new LABStudyOptionAttributeValue()
                            {
                                idLABStudy = labStudyDest.idLABStudy,
                                idOptionAttribute = labStudyOptAttrValueSource.idOptionAttribute,
                                idLABStudyOptionValue = newLabStudyOptionValue.idLABStudyOptionValue,
                                Value = labStudyOptAttrValueSource.Value,
                                DateCreated = DateTime.Now
                            };

                            //Add LabStudyOptionAttributeValue to DB : don't save yet
                            newLabStudyOptionValue.LABStudyOptionAttributeValue.Add(newLabStudyOptionAttrValue);
                        }
                    }
                }

                //3- Commit all changes here
                db.SaveChanges();
            }

        }