Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception handling in Entity Framework

I have a form that it has some field and has relationship with database. I'm using entity framework I wanna handle exception before sql server send error message. For example when user enter string value in number field win or web application handle exception before sql server handle it. I wrote this code but it don't work for all the exception. For example if field was empty or has invalid type said input string is not in 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);
                }
             }
        } 
like image 548
heavy Avatar asked Nov 16 '13 05:11

heavy


People also ask

What is exception handling in .NET framework?

NET Framework, an exception is an object that inherits from the System. Exception class. An exception is thrown from an area of code where a problem has occurred. The exception is passed up the call stack to a place where the application provides code to handle the exception.

What is exception handling Handling?

Exception handling is the process of responding to unwanted or unexpected events when a computer program runs. Exception handling deals with these events to avoid the program or system crashing, and without this process, exceptions would disrupt the normal operation of a program.

What is exception handling explain with example?

Examples include a user providing abnormal input, a file system error being encountered when trying to read or write a file, or a program attempting to divide by zero. Exception handling attempts to gracefully handle these situations so that a program (or worse, an entire system) does not crash.


3 Answers

What you should do is finding a architecture which is fits your solution model. In general I would do validation before creating the context. If you need more validation in your application you may want to create a validation layer 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;
            }
        }
    }
}

Hope the example make more clearer the architecture about validation logic.

like image 182
Yusuf Uzun Avatar answered Oct 20 '22 23:10

Yusuf Uzun


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:

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.

like image 36
LazyDog Avatar answered Oct 20 '22 22:10

LazyDog


Instead of catching Exception you should catch SqlException.

SqlException has a number property that you can use:

catch (SqlException e)
{
   MessageBox.Show("Error number: "+e.Number + " - " + e.Message);
}
like image 25
Shiraz Bhaiji Avatar answered Oct 20 '22 22:10

Shiraz Bhaiji