public IActionResult PostPrescriptions(PostPrescriptionRequest request) { PostPrescriptionResponse prescriptionsResponse; IActionResult response; try { prescriptionsResponse = _dbService.PostPrescription(request); response = Ok(prescriptionsResponse); } catch (Exception e) { response = NotFound(e.Message); } return(response); }
public PostPrescriptionResponse PostPrescription(PostPrescriptionRequest request) { PostPrescriptionResponse response; if (DateTime.Compare(request.DueDate, request.Date) <= 0) { throw new Exception("Due date is smaller than date"); } using (var connection = new SqlConnection(_connectionString)) using (var command = new SqlCommand()) { connection.Open(); command.Connection = connection; var transaction = connection.BeginTransaction(); command.Transaction = transaction; command.CommandText = "select * from Doctor where IdDoctor = @IdDoctor;"; command.Parameters.AddWithValue("IdDoctor", request.IdDoctor); command.Parameters.Clear(); using (var reader = command.ExecuteReader()) { if (!reader.HasRows) { transaction.Rollback(); throw new Exception($"No doctors with IdDoctor: {request.IdDoctor}"); } } command.CommandText = "select * from Patient where IdPatient = @IdPatient;"; command.Parameters.AddWithValue("IdPatient", request.IdPatient); command.Parameters.Clear(); using (var reader = command.ExecuteReader()) { if (!reader.HasRows) { transaction.Rollback(); throw new Exception($"No patients with IdPatient: {request.IdPatient}"); } } int idPrescription; command.CommandText = "select count(*)+1 as newId from Prescription ;"; using (var reader = command.ExecuteReader()) { if (!reader.HasRows) { transaction.Rollback(); throw new Exception($"Failed counting rows!"); } idPrescription = int.Parse(reader["newId"].ToString()); } command.CommandText = "insert into Prescription(IdPrescription, Date, DueDate, IdPatient, IdDoctor) " + "values (@IdPrescription, @Date, @DueDate, @IdPatient, @IdDoctor);"; command.Parameters.AddWithValue("IdPrescription", idPrescription); command.Parameters.AddWithValue("Date", request.Date); command.Parameters.AddWithValue("DueDate", request.DueDate); command.Parameters.AddWithValue("IdPatient", request.IdPatient); command.Parameters.AddWithValue("IdDoctor", request.IdDoctor); command.Parameters.Clear(); using (var reader = command.ExecuteReader()) { response = new PostPrescriptionResponse { IdPrescription = idPrescription, Date = request.Date, DueDate = request.DueDate, IdDoctor = request.IdDoctor, IdPatient = request.IdPatient }; } } return(response); }