0

I'm using EF in my application and it is throwing an exception

System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details. at System.Data.Entity.Internal.InternalContext.SaveChanges() at Capture.Controllers.HomeController.AddFirstVisit(Int32 companyId)

I can see what I need to do to learn about the error - I need to see EntityValidationErrors but the problem is I can't debug - the code needs to be run the server so running locally does not reproduce this error.

The problem I have is, without seeing the object, how to do I get the execption out as a string?

At the moment my I use catch(Exception e) and pass e.ToString() to my logging engine.

How do I pass the error detail? I'm hoping something like

catch(Exception e)
{
    e.innerException.EntityValidationErrors; // what should this be
}

This almost had the answer EF Code First: How do I see 'EntityValidationErrors' property from the nuget package console? but I don't get the option of e.EntityValidationErrors

Community
  • 1
  • 1
MyDaftQuestions
  • 4,487
  • 17
  • 63
  • 120
  • 2
    Use a remote debugger.https://msdn.microsoft.com/en-us/library/y7f5zaaa.aspx – JNYRanger Mar 05 '15 at 19:18
  • What an amazing answer – MyDaftQuestions Mar 05 '15 at 19:18
  • Not sure if sarcasm or not haha. Are you using a specific logging framework? Some have this feature built in – JNYRanger Mar 05 '15 at 19:27
  • 1
    @JNYRanger, not sarcasm, I'm not the typical SO user!! :) I had no idea you could do remote debugging, it's very genuine, than you – MyDaftQuestions Mar 05 '15 at 19:36
  • 2
    You may want to also consider some drop in logging engines such as Elmah and stop catching and logging just the message in the way that you are doing. Stack trace is at least as important in most cases. http://www.hanselman.com/blog/ELMAHErrorLoggingModulesAndHandlersForASPNETAndMVCToo.aspx – Paddy Mar 05 '15 at 19:38

3 Answers3

4

Assuming Log(string) logs to your logging engine:

catch (DbEntityValidationException ex)
{
   foreach (var evr in ex.EntityValidationErrors)
   {
      foreach (var error in evr.ValidationErrors)
      {
         Log(error.PropertyName + ": " + error.ErrorMessage);
      }
   }   
}
Eugene Osovetsky
  • 6,443
  • 2
  • 38
  • 59
1

I've created a class to handle modelstate erros.

public class Message
    {
        public string Title { get; set; }
        public string Mensagem { get; set; }
        public List<string> Itens { get; set; }
        public string itensRetorno { get; set; }

        public Message()
        {
            this.Itens = new List<string>();
        }

        public void Add(string item)
        {
            this.Itens.Add(item);
        }

        public string GetMessages()
        {
            var MsgItens = string.Empty;

            foreach (var item in this.Itens)
            {
                MsgItens += "<li>" + item + "</li>";
            }

            this.itensRetorno = MsgItens;

            return MsgItens;
        }


public static class ModelStateUtils
    {
        public static Message GetModelStateErrors(ModelStateDictionary modelState)
        {
            Message msg = new Message();

            List<string> errorKeys = new List<string>();

            int index = 0;

            foreach (var val in modelState.Values)
            {
                if (val.Errors.Count() > 0)
                {
                    msg.Itens.Add(modelState.Keys.ElementAt(index));
                }

                index++;
            }

            msg.Title = "Erro";
            msg.Mensagem = "Os seguintes campos são obrigatórios<br />" + msg.GetMessages();

            return msg.Itens.Count() > 0 ? msg : null;
        }
    }
Márcio Gonzalez
  • 1,020
  • 1
  • 8
  • 20
0

Catch the more specific exception first:

catch(DbEntityValidationException e)
{
    // Do something with e.EntityValidationErrors; 
}
catch(Exception e)
{
    // Do whatever you were already doing with the generic exception
}
Joel C
  • 5,547
  • 1
  • 21
  • 31