find out the exact entity causing an exception in entity framework

前端 未结 2 797
悲&欢浪女
悲&欢浪女 2021-02-02 18:39

The entity framework gives me generic messages in the exception without telling me the exact entity and the attribute which caused the error. How do I get more information about

相关标签:
2条回答
  • 2021-02-02 18:43

    Here's the code I have in my solution:

    try
    {
        _context.SaveChanges();
    }
    catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
    {
        Exception raise = dbEx;
        foreach (var validationErrors in dbEx.EntityValidationErrors)
        {
            foreach (var validationError in validationErrors.ValidationErrors)
            {
                string message = string.Format("{0}:{1}", validationErrors.Entry.Entity.ToString(), validationError.ErrorMessage);
                //raise a new exception inserting the current one as the InnerException
                raise = new InvalidOperationException(message , raise);
            }
        }
        throw raise;
    }
    

    You can use it as a basis to add into your solution ... it builds a nested set of exceptions with all the details from Entity Framework.

    0 讨论(0)
  • 2021-02-02 18:50

    You need to write tests for repositories and in the base class for your tests:

    try
    {
        DbContext.SaveChanges();
    }
    catch (DbEntityValidationException e)
    {
        e.EntityValidationErrors.SelectMany(error => error.ValidationErrors).ToList().ForEach(
        item => Console.WriteLine("{0} - {1}", item.PropertyName, item.ErrorMessage));
        throw;
    }
    
    0 讨论(0)
提交回复
热议问题