public Mapper Get(string targetId, string svaId, string studyId) { try { // 1. get list of values for this Variable from MICA List <variable_vw> MicaVars = _Micarepo.GetVariableValuesByVariable(targetId, studyId).ToList(); Mapper mapper = _repo.GetMapperByVariables(targetId, svaId); // 2. If no Mapper record exists (for this target and sva) then // a. Create a new mapper and one maprecord for each target value if (mapper == null) { Mapper m = new Mapper { StudyVariableAttributeId = svaId, TargetFieldId = targetId, MapRecs = new List <MapRecord>() }; foreach (variable_vw v in MicaVars) { m.MapRecs.Add(new MapRecord { TargetFieldId = v.nid.ToString(), TargetFieldName = v.title, TargetLabel = v.field_variable_categories_label, TargetValue = v.field_variable_categories_name, TargetMissing = v.field_variable_categories_missing.ToString(), TargetType = v.field_value_type_value, TargetUnits = v.field_unit_value, CreatedDate = DateTime.Now, CreatedBy = System.Web.HttpContext.Current.User.Identity.Name }); } // In the API - we get the value of m through the body of the message as opossed to parameters if (_repo.AddMapper(m) && _repo.Save()) { return(m); } return(m); } else { // 3. If any target value does not have a maprecord then // a. Create a new maprecord for that value foreach (variable_vw v in MicaVars) { // if the record exists update it with any new MICA info if (mapper.MapRecs.Any(o => o.TargetValue == v.field_variable_categories_name)) { MapRecord mr = mapper.MapRecs.Where(o => o.TargetValue == v.field_variable_categories_name).First(); mr.TargetFieldId = v.nid.ToString(); mr.TargetFieldName = v.title; mr.TargetLabel = v.field_variable_categories_label; mr.TargetValue = v.field_variable_categories_name; mr.TargetMissing = v.field_variable_categories_missing.ToString(); mr.TargetType = v.field_value_type_value; mr.TargetUnits = v.field_unit_value; mr.ModifiedDate = DateTime.Now; mr.ModifiedBy = System.Web.HttpContext.Current.User.Identity.Name; } else // insert a new record with MICA data { mapper.MapRecs.Add(new MapRecord { TargetFieldId = v.nid.ToString(), TargetFieldName = v.title, TargetLabel = v.field_variable_categories_label, TargetValue = v.field_variable_categories_name, TargetMissing = v.field_variable_categories_missing.ToString(), TargetType = v.field_value_type_value, TargetUnits = v.field_unit_value, CreatedDate = DateTime.Now, CreatedBy = System.Web.HttpContext.Current.User.Identity.Name }); } } } // 4. return Mapper records return(mapper); } catch (Exception ex) { string x = ex.Message; return(null); } }