异常记录抛出空引用错误

时间:2016-04-12 09:52:35

标签: c# entity-framework exception nullpointerexception

我正在尝试使用实体框架将异常记录到sqlserver 2012数据库中,但是当我的代码进入保存到数据库的阶段时,我收到错误说

  

System.NullReferenceException未被用户代码
处理   HResult = -2147467261 Message =对象引用未设置为实例   一个对象。

我已粘贴我的代码

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

我也试过

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

上面的代码在context.SaveChanges上给出了一个错误“System.Data.Entity.Validation.DbEntityValidationException未被用户代码处理   的HResult = -2146232032   消息=一个或多个实体的验证失败。有关详细信息,请参阅“EntityValidationErrors”属性。   源=的EntityFramework“

1 个答案:

答案 0 :(得分:0)

这一行:

var exceptionEntity = context.tbl_Audit_SystemLog.FirstOrDefault();
如果tbl_Audit_SystemLog中没有行,则

将返回null,这将导致下一行给出NullReferenceException