Exception handling in Entity Framework

asp.net c# c#-4.0 entity-framework

Question

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);
                }
             }
        } 
1
7
11/16/2013 5:22:42 AM

Accepted Answer

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.

0
11/17/2013 8:30:05 PM

Popular Answer

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.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow