title: Exception Logging throwing null reference error
body: <p>I am trying to log exceptions into a sqlserver 2012 database using entity framework however when my code gets to the stage of saving into the database I get an error saying</p>
  
  <blockquote>
    <p>System.NullReferenceException was unhandled by user code<br>
    HResult=-2147467261   Message=Object reference not set to an instance
    of an object.</p>
  </blockquote>
  
  <p>I have pasted my code below </p>
  
  <pre><code>public IEnumerable&lt;SensorMetricItem&gt; GetDeviceSensorDashboardDetails(int AssetInstanceId)
  {
      try
      {
          using (var context = new EnigmaEntities())
          {
              var dashboardSensorEntities = context.usp_Read_DeviceSensorDashboardDetails_List(AssetInstanceId).ToList();
              return dashboardSensorEntities.Select(rd =&gt; new SensorMetricItem(rd.sensorId, rd.AssetInstanceID, rd.exception, rd.sensorDesc, rd.Total ?? 0, rd.Abbreviation, rd.sensorGuid)).ToList();
          }
      }
      catch (Exception ex)
      {
          SendExcepToDB(ex);  
          return null;
      }
  }
  public static void SendExcepToDB(Exception exdb)
  {
      using (var context = new EnigmaEntities())
      {
          var exceptionEntity = context.tbl_Audit_SystemLog.FirstOrDefault();
          exceptionEntity.ErrorMessage = exdb.Message.ToString();
          context.SaveChanges();
      }
  }   
  </code></pre>
  
  <p>I have also tried </p>
  
  <pre><code>public  void SendExcepToDB(Exception exdb)
      {
  
          using (var context = new EnigmaEntities())
          {
              var exceptionEntity = new tbl_Audit_SystemLog
              {
                  ErrorMessage = exdb.Message,
                  ServiceID = 0, 
                  FunctionName = "",
                  Version = "", 
                  StackTrace = "" , 
                  Severity = "" , 
                  URL = "" , 
                  UserID = 0,
                  CreatedAt = DateTime.Now
  
              };
  
          context.tbl_Audit_SystemLog.Add(exceptionEntity);
          context.SaveChanges();
  </code></pre>
  
  <p>the code above gives me an error on context.SaveChanges "System.Data.Entity.Validation.DbEntityValidationException was unhandled by user code
    HResult=-2146232032
    Message=Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
    Source=EntityFramework"</p>