Exception handling in Entity Framework

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

Accepted Answer

Finding an architecture that matches your solution model is what you should do. Generally speaking, I would perform validation prior to constructing the context. You might want to add a validation layer if your application requires more validation.

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;
            }
        }
    }
}

I hope the example makes the design regarding validation logic more clear.

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

Popular Answer

Prior to handling specific Entity Framework problems, you ought to perform UI validation.

Use data annotations to build a model:

using System.ComponentModel.DataAnnotations;
public class YourViewModel
    {
        [Required]
        [Range(0, 15, ErrorMessage = "Can only be between 0 .. 15")]
        public int stNumber { get; set; }
    }

Return the model from your controller to the view:

var model = new YourViewModel();
return View(model);

By including the model in your view and making use of some tag helpers, you can bind your textbox to the model:

@using YourProject.WebUI.Models
@model YourViewModel  

@Html.TextBoxFor(m => m.stNumber )
@Html.ValidationMessageFor(m => m.stNumber )

Now, before incorrect data is ever transmitted back to the controller, an error will be presented to the user if someone tries to enter a non-numeric or a number that is out of range.

Use a try-catch to handle Entity Framework exceptions:

        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

Sending modifications to the database experienced a problem.

DbUpdateConcurrencyException

The anticipated number of rows was unaffected by any database commands. This typically denotes an optimistic concurrency violation, which means that a database row has changed since it was requested.

DbEntityValidationException

Because entity property values could not be validated, the save was canceled.

NotSupportedException

The usage of unsupported behavior, such as running several asynchronous commands simultaneously on the same context instance, was attempted.

ObjectDisposedException

The connection or context has been dropped.

InvalidOperationException

Before or after sending commands to the database, an error occurred when trying to process entities in the context.



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