Exception Handling in the Entity Framework

I have a form in which there is some kind of field and has a connection to the database. I am using an entity structure I want to handle an exception before sending an SQL server error message. For example, when a user enters a string value in the win number or exception of a web application processing field before the SQL server processes it. I wrote this code, but it does not work for all exceptions. For example, if the field is empty or has an invalid type, the specified input string is not in the correct format.

using (var context = new entityTestEntities2()) { try { int stNumber = Convert.ToInt32(textBox2.Text); var allCustomers = context.setcust(null, stNumber); } catch(Exception ex) { if (ex.Message.Contains("correct format")) { int x= System.Runtime.InteropServices.Marshal.GetExceptionCode(); MessageBox.Show("error number"+x.ToString()+ex.Message); } } } 
+6
source share
3 answers

What you need to do is find an architecture suitable for your solution model. In general, I would do a check before creating the context. If you need additional verification in your application, you can create a verification level for this purpose.

 public class RuleViolation { public string Property {get; set;} public string Message {get; set;} } public class Program { public static List<RuleViolation> GetRuleViolations(string[] parameters) { List<RuleViolation> validations = new List<RuleViolation>(); if(!int.TryParse(parameters[0], out new Int32())) { validations.Add(new RuleViolation{Message ="Input1 must be integer.", Property = "input1"}); } //more validation return validations; } public static void Main(string[] parameters) { var validations = GetRuleViolations(parameters); if(validations.Any()) { validations.ForEach(x=> Console.WriteLine(x.Message)); return; } int input1 = int.Parse(parameters[0]); //after all your business logic are ok, then you can go to persistence layer to hit the database. using (var context = new entityTestEntities2()) { try { var allCustomers = context.setcust(null, input1); } catch(SqlException exc) { //here you might still get some exceptions but not about validation. ExceptionManager.Log(exc); //sometimes you may want to throw the exception to upper layers for handle it better over there! throw; } } } } 

We hope the example simplifies the validation logic architecture.

0
source

Instead of catching an Exception, you should catch a SqlException.

SqlException has a number property, which you can use:

 catch (SqlException e) { MessageBox.Show("Error number: "+e.Number + " - " + e.Message); } 
+3
source

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.

+2
source

Source: https://habr.com/ru/post/958184/


All Articles