find out the exact entity causing an exception in entity framework

前端 未结 2 798
悲&欢浪女
悲&欢浪女 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.

提交回复
热议问题