You must first check in the user interface, and then handle certain errors related to the 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 the text box 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 value or a number that is outside the valid range, an error will be displayed to the user before the data is sent back to the controller.
To handle Entity Framework exceptions, use 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 types of exceptions include:
DbUpdateException
An error occurred while sending updates to the database.
DbUpdateConcurrencyException
The database command did not affect the expected number of rows. This usually indicates an optimistic concurrency violation; that is, the row has been modified in the database since it was requested.
DbEntityValidationException
Saving was interrupted because it was not possible to verify the validity of the object properties.
NotSupportedException
An attempt was made to use unsupported behavior, such as executing multiple asynchronous commands simultaneously in the same context instance.
ObjectDisposedException
The context or connection has been deleted.
InvalidOperationException
Some error occurred while trying to process entities in context before or after sending commands to the database.