Error Handling in Entity Framework Example

Here we learn how to handle error in Entity Framework, details exception handling techniques example in C#.

Error handling is very important aspect in application development life cycle, there are many different ways error handling is implemented, while developing any application.

In this tutorial you will learn how to implement error handling in entity framework, so we can catch the right error at data access layer and make the required changes to fix the error.

One simple step to implement error handling could be using try catch block like example below.

try
    {
        using (var context = new Entities())
        {
            var query = from c in context.vwProduct
                        join o in context.tbOfferProduct on c.ProductId equals o.ProductId
                        where (o.OfferId == offerId)
                        select c;
            products = query.ToList<vwProduct>();
        }
    }
catch (Exception ex)
{
    ErrorDTO.TrackError(ex);
}

But above example may not be sufficient to know what the error is!

It will throw very common message or error in inner exception property, which may not reveal the actual error.

So, we will implement DbEntityValidationException, which will catch some entity specify error details.

catch (DbEntityValidationException e)
{
    ErrorDTO.TrackError(e.InnerException);
}

Above same example can be written differently like example below, this will help us to know exactly which field is causing error, and what type of error is that.

entity framework exception handling example

In following example, I am looping through the entity collection can catching exception details in a string builder object.

catch (DbEntityValidationException e)
{
    StringBuilder strErr = new StringBuilder();
    foreach (var eve in e.EntityValidationErrors)
    {
       
        strErr.Append($"Entity of type {eve.Entry.Entity.GetType().Name}" +
        $"in the state {eve.Entry.State} "+
        $"has the following validation errors:");


        foreach (var ve in eve.ValidationErrors)
        {
            strErr.Append($"Property: {ve.PropertyName}," +
                $" Error: {ve.ErrorMessage}");
        }


        foreach (var ve in eve.ValidationErrors)
        {
            strErr.Append($"Property: {ve.PropertyName}, " +
                $"Value: {eve.Entry.CurrentValues.GetValue<object>(ve.PropertyName)}," +
                $" Error: {ve.ErrorMessage}");
        }


    }
        ErrorDTO.TrackError("AddProduct", strErr.ToString());
}

Apart from above DbEntityValidationException, there are few other type of exception, which are also helpful in some scenario, like EntityCommandExecutionException, DbUpdateException etc.

Here is the complete exception handling implementation example, Notice, how to catch Entity Validation Errors in following code

    
using System.Data.Entity.Validation;
using System.Data.Entity.Infrastructure;
using System.Data.Entity;
using System.Data.Entity.Core;


public List<vwProduct> GetProductsByOffer(long offerId)
        {
            List<vwProduct> products = null;
            try
            {
                using (var context = new Entities())
                {
                    var query = from c in context.vwProduct
                                join o in context.tbOfferProduct on c.ProductId equals o.ProductId
                                where (o.OfferId == offerId)
                                select c;
                    products = query.ToList<vwProduct>();
                }
            }
    catch (DbEntityValidationException e)
    {
        StringBuilder strErr = new StringBuilder();
        foreach (var eve in e.EntityValidationErrors)
        {
        strErr.Append($"Entity of type {eve.Entry.Entity.GetType().Name}" +
        $"in the state {eve.Entry.State} "+
        $"has the following validation errors:");
        foreach (var ve in eve.ValidationErrors)
        {
            strErr.Append($"Property: {ve.PropertyName}," +
                $" Error: {ve.ErrorMessage}");
        }
        foreach (var ve in eve.ValidationErrors)
        {
            strErr.Append($"Property: {ve.PropertyName}, " +
                $"Value: {eve.Entry.CurrentValues.GetValue<object>(ve.PropertyName)}," +
                $" Error: {ve.ErrorMessage}");
        }
        }
        ErrorDTO.TrackError("AddProduct", strErr.ToString());
    }
    catch (DbUpdateException ex)
    {
        ErrorDTO.TrackError(ex.Source, ex.InnerException);
    }
    catch (EntityCommandExecutionException cex)
    {
        ErrorDTO.TrackError(cex.InnerException);
    }
    catch (Exception ex)
    {
        ErrorDTO.TrackError(ex);
    }
    return products;
        }
			

ex {"An error occurred while executing the command definition. See the inner exception for details."} System.Exception {System.Data.Entity.Core.EntityCommandExecutionException}

While dealing with complex entity, we should think of implementing all possible exception type, so the code can catch the exact error message and provide the log details to developers, it will be easy to fix the error quickly.

 
EF Core Update example
Learn entity framework orm using c#, entity framework core and earlier version of entity framework, all tutorials are written in c#.
Entity Framework Interview Questions

SQL interview questions
Entity Framework C# Examples | Join .Net C# Course