SingleOrDefault()似乎正在引发System.NullReferenceException

本文关键字:System NullReferenceException SingleOrDefault | 更新日期: 2023-09-27 18:20:29

SingleOrDefault()的文档表明它可以返回两个异常之一:

Exception                     Condition
ArgumentNullException         source is null.  
InvalidOperationException     The input sequence contains more than one element.

考虑到这一点,下面的代码怎么会返回NullReferenceException

//--------------------------------------------------------------------------------------------        
public Domain.Data.ServiceJob SelectByServiceJobID(int serviceJobID)
{
    using (_dataContext = new ServiceJobDataDataContext(_systemService.GetCurrentSystem().WriteOnlyDatabase.ConnectionString))
    {
        try
        {
            Domain.Data.ServiceJob result = new Domain.Data.ServiceJob();
            Mapper.CreateMap<LINQ.ServiceJob, Domain.Data.ServiceJob>();
            //THIS STATEMENT BELOW HAS TO BE THROWING A NullReferenceException
            ServiceJob linqList = _dataContext.ServiceJobs.Where(p => p.ServiceJobID == serviceJobID).SingleOrDefault();  
            //Broke the above statement up to debug sporadic exception here - linqList should never be null
            if(linqList!=null)                    
                result=Mapper.Map<ServiceJob, Domain.Data.ServiceJob>(linqList);
            return result;
        }catch(Exception e)
        {
            //Added this to catch the sporadic phantom error
            throw new Exception(String.Format("SelectByServiceJobID({0}) ERROR : {1}",serviceJobID,e.ToString());
        }
    }
}

这是我的堆栈轨迹。

xxxxx.Services.ServiceAgent.DoWork - System.Exception: SelectByServiceJobID(22) ERROR : System.NullReferenceException: Object reference not set to an instance of an object.
   at System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult)
   at System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries)
   at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query)
   at System.Data.Linq.DataQuery`1.System.Linq.IQueryProvider.Execute[S](Expression expression)
   at System.Linq.Queryable.SingleOrDefault[TSource](IQueryable`1 source)
   at xxxxx.Resources.Data.LINQ.ServiceJobService.SelectByServiceJobID(Int32 serviceJobID)
   at xxxxx.Resources.Data.LINQ.ServiceJobService.SelectByServiceJobID(Int32 serviceJobID)
   at xxxxx.Controllers.Data.ServiceJobController.SelectByServiceJobID(Int32 serviceJobID)
   at xxxxx.Services.ServiceAgent.xxxxxServiceAgent.DoWork()

以下是如何在服务代码中访问该数据调用。

public void DoWork()
{
    ....  
    ServiceJob serviceJob=new ServiceJobController().SelectByServiceJobID(thisServiceJob.ServiceJobID);
    if (serviceJob.ServiceJobStatusID  != (int)ServiceJobStatusEnum.Stopped)
    {                                
        //Time to do some work
        _ThreadPool.AddWorkItem(new ThreadPoolWorkItem(thisServiceJob.ServiceJobID, true, true, 1, new SJDelegate(doWorkForServiceJob),thisServiceJob));
    }
    else
    {
        //set status to stopped                              
        thisServiceJob.ServiceJobStatusID = serviceJob.ServiceJobStatusID;                                
    }
}

SingleOrDefault()似乎正在引发System.NullReferenceException

我通过反复试验找到了答案。出于某种原因,使用具有相同名称的私有类作用域变量_dataContext和函数作用域变量导致了此问题。当我从所有存储库类中删除类范围的变量_dataContext时,这些错误就停止了。0_o

public class myClass
{
    private _dataContext =new ServiceJobDataDataContext(_systemService.GetCurrentSystem().WriteOnlyDatabase.ConnectionString);
    public Domain.Data.ServiceJob SelectByServiceJobID(int serviceJobID)
    {
        using (_dataContext = new ServiceJobDataDataContext(_systemService.GetCurrentSystem().WriteOnlyDatabase.ConnectionString))
        {
         //...
        }  
    }
}

NullReferenceException可以在"试图取消引用null对象引用"的任何时候抛出(根据MSDNhttps://msdn.microsoft.com/en-us/library/vstudio/system.nullreferenceexception%28v=vs.110%29.aspx)。这意味着任何试图在null对象上调用方法或属性的代码都会调用此执行。

我怀疑您的LINQ查询(Where())正在返回null。

您对文档是正确的。我很快查找了ArgumentNullException:的定义

备注

当调用一个方法并且至少有一个传递的参数为null,但不应为null时,会引发ArgumentNullException异常msdn docu

你不会通过争论。但是在某个迭代中调用方法的对象为null(_dataContext.ServiceJobs不包含服务作业ID 22)

在调用.SingleOrDefault(); 之前验证该部件_dataContext.ServiceJobs.Where(p => p.ServiceJobID == serviceJobID)是否为空

谨致问候,Butti