public ReportDefinitionsMap() { CreateMap <ReportDefinition, ReportDefinitionVM>() .ForMember(v => v.id, opt => opt.MapFrom(d => d.ID)) .ForMember(v => v.columns, opt => opt.MapFrom(d => JsonConvert.DeserializeObject(d.columnsJson))) .ForMember(v => v.inputs, opt => opt.MapFrom(d => JsonConvert.DeserializeObject(d.inputsJson))) ; CreateMap <ReportDefinitionVM, ReportDefinition>() .ForMember(d => d.ID, opt => opt.MapFrom(v => v.id)) .ForMember(d => d.inputsJson, opt => opt.MapFrom(v => JsonConvert.SerializeObject(v.inputs))) .ForMember(d => d.columnsJson, opt => opt.MapFrom(v => JsonConvert.SerializeObject(v.columns))) .ForMember(d => d.name, opt => opt.MapFrom(v => MapperHelpers.NormalizeName(v.commonName))) ; }
public ActionResult <ReportDefinitionVM> Create([FromBody] ReportDefinitionVM reportDefinitionVM) { /*** * Applies to both Put and Create * Return all errors in the format: * new { errors = errorLabel, errorsList) } * where label is a string and error list is a list of strings * You can use the private method ArrangeReportErrors() to simply return * new { errors = ArrangeReportErrors("sqlQuery", validationMessages) } * The frontend client expects this as it is also the format that is returned * with ModelState errors. ***/ if (!ModelState.IsValid) { return(BadRequest(ModelState)); } // if common name converted to name as ID already exists if (serv.Exists(MapperHelpers.NormalizeName(reportDefinitionVM.commonName))) { return(BadRequest("Report with this name already exists")); } string query = reportDefinitionVM.sqlquery; try { var validationMessages = serv.ValidateQuery(query); if (validationMessages.Count == 0) { var createdRecord = serv.Create(map.Map <ReportDefinition>(reportDefinitionVM), UserEmail); // return StatusCode((int)HttpStatusCode.OK); return(CreatedAtAction(nameof(Get), new { createdRecord.name }, new { data = map.Map <ReportDefinitionVM>(createdRecord) })); } else { // 400; we wanted validation messages, and got them. return(BadRequest(new { errors = ArrangeReportErrors("sqlQuery", validationMessages) })); } } catch (Exception ex) { // SQL errors are expected but they will be returned as strings (400). // in this case, something happened that we were not expecting; return 500. var message = ex.Message; return(StatusCode((int)HttpStatusCode.InternalServerError, new { errors = ArrangeReportErrors("Server Error", new List <string>() { ex.Message }) })); } }