0

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

System.NullReferenceException was unhandled by user code
HResult=-2147467261 Message=Object reference not set to an instance of an object.

I have pasted my code below

public IEnumerable<SensorMetricItem> GetDeviceSensorDashboardDetails(int AssetInstanceId)
{
    try
    {
        using (var context = new EnigmaEntities())
        {
            var dashboardSensorEntities = context.usp_Read_DeviceSensorDashboardDetails_List(AssetInstanceId).ToList();
            return dashboardSensorEntities.Select(rd => 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();
    }
}   

I have also tried

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();

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"

Zidane
  • 1,696
  • 3
  • 21
  • 35

1 Answers1

0

This line:

var exceptionEntity = context.tbl_Audit_SystemLog.FirstOrDefault();

will return null if there are no rows in tbl_Audit_SystemLog, which will cause the next line to give a NullReferenceException

Richard
  • 29,854
  • 11
  • 77
  • 120
  • your suggestion helped thanks , do you know how I can get the name of the method in which the exception occurs so that I can save to database – Zidane Apr 12 '16 at 10:49