Scenario: I am using a helper class called 'OutputHelper' to add a new record to the table 'Output'. My 'Output' object contains the following:
- ShiftID
- Model
- WorksOrder
- LotNo
- Quantity
- ShiftHour
I do not want a record to be added if a record already exists with the ShiftID and ShiftHour of the record that I am trying to add.
The way I am achieving this currently is having the property 'RecordOutput' in the helper class try and add the record then return a string which I handle with a switch statement and provide feedback to the user accordingly.
This seems to be working fine but I can't help but think it's a terrible way of doing things. Can anyone provide any feedback and suggestions for improvement?
Output helper class:
public class OutputHelper
{
public string RecordOutput(Models.Output output)
{
var shiftId = output.ShiftID;
var shiftHour = output.ShiftHour;
using (var db = new TestContext())
{
try
{
if (db.Outputs.Any(x => x.ShiftID == shiftId && x.ShiftHour == shiftHour))
{
return "Exists";
}
db.Outputs.Add(output);
db.SaveChanges();
}
catch (Exception)
{
return "NotSaved";
}
return "Success";
}
}
}
Code from button click on form
var outputHelper = new OutputHelper();
switch (outputHelper.RecordOutput(output))
{
case "Exists":
lblErrorMessage.Text = "Output already recorded for this timeframe";
failMessage.Visible = true;
break;
case "Not Saved":
lblErrorMessage.Text = "There was a problem saving this record. Please try again";
failMessage.Visible = true;
break;
default:
lblSuccess.Text = "Output record added to database";
successMessage.Visible = true;
ResetForm();
break;
}