You should do validation on the UI first then handle specific errors related to Entity Framework.
Create a Model and use data annotations :
using System.ComponentModel.DataAnnotations;
public class YourViewModel
{
[Required]
[Range(0, 15, ErrorMessage = "Can only be between 0 .. 15")]
public int stNumber { get; set; }
}
In your controller return the model to the view:
var model = new YourViewModel();
return View(model);
Bind your textbox to the model by adding the model to your view and using some tag helpers:
@using YourProject.WebUI.Models
@model YourViewModel
@Html.TextBoxFor(m => m.stNumber )
@Html.ValidationMessageFor(m => m.stNumber )
Now when someone tries to enter a non numeric or a number that is out of range an error will be displayed to the user before bad data is ever sent back to the controller.
To handle Entity Framework exceptions use a try catch:
try
{
var entity = context.yourEntity.FirstOrDefault(o => o.Id == custId);
if (entity == null) return false;
entity.value= stNumber;
entity.ModifiedBy = userId;
entity.ModifiedDate = DateTime.Now;
Db.SaveChanges();
return true;
}
catch (DbUpdateException Ex)
{
Console.WriteLine(Ex.InnerException.Message);
return false;
}
Other Exception types include (from here):
DbUpdateException An error occurred sending updates to the
database.
DbUpdateConcurrencyException A database command did not affect the
expected number of rows. This usually indicates an optimistic
concurrency violation; that is, a row has been changed in the database
since it was queried.
DbEntityValidationException The save was aborted because
validation of entity property values failed.
NotSupportedException An attempt was made to use unsupported
behavior such as executing multiple asynchronous commands concurrently
on the same context instance.
ObjectDisposedException The context or connection have been
disposed.
InvalidOperationException Some error occurred attempting to process
entities in the context either before or after sending commands to the
database.
Integer.TryParsefor input from textboxes.