SaveChanges() from an EntityFramework context fails silently

.net c# entity-framework entity-framework-6

Question

I am using an Entity Framework 6.1 Model from Database 'wizard' setup. When I create a Business object from my context and then try to add for attachment and then SaveChanges() nothing happens. Is there a tracing mode? or something I can turn on to see what is really happened under the covers.

Simple example:

 var fb = _context.Business.Create();
 //fb.Id exists and is an int but it is auto incr in the db
 fb.Name = ub.ACCOUNT_NAME;
 fb.ServiceManager = ub.SERVICE_MANAGER;
 fb.AccountManager = ub.ACCOUNT_MANAGER;
 fb.SalesPerson = ub.SALESPERSON;
 fb.Created = DateTime.UtcNow;
 fb.Updated = DateTime.UtcNow;
 _context.Add(fb);
 _context.SaveChanges();
1
2
6/30/2014 10:12:07 PM

Accepted Answer

The best way I have found to catch EF errors is by overriding the SaveChange method like below. If you have a centered place to recover logs (like log4net), the function will be able to insert it there.

public partial class Business
{
    /// <summary>Override the SaveChange to return better error messages</summary>
    public override int SaveChanges()
    {
        try {
            return base.SaveChanges();
        }
        catch (System.Data.Entity.Validation.DbEntityValidationException ex) {
            // Retrieve the error messages as a list of strings.
            var errorMessages = ex.EntityValidationErrors
                    .SelectMany(x => x.ValidationErrors)
                    .Select(x => x.ErrorMessage);

            // Join the list to a single string.
            var fullErrorMessage = string.Join("; ", errorMessages);

            // Combine the original exception message with the new one.
            var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);

            // Add some logging with log4net here


            // Throw a new DbEntityValidationException with the improved exception message.
            throw new System.Data.Entity.Validation.DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);

        }
    }
7
7/2/2014 1:53:11 PM

Popular Answer

Have you tried creating a new Business object and adding it in? instead of creating one first?

 var fb = new Business();
 //fb.Id exists and is an int but it is auto incr in the db
 fb.Name = ub.ACCOUNT_NAME;
 fb.ServiceManager = ub.SERVICE_MANAGER;
 fb.AccountManager = ub.ACCOUNT_MANAGER;
 fb.SalesPerson = ub.SALESPERSON;
 fb.Created = DateTime.UtcNow;
 fb.Updated = DateTime.UtcNow;
 _context.Business.Add(fb);
 _context.SaveChanges();


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