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

最佳答案

我通过反复试验找到了答案。出于某种原因,使用私有类范围的变量_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))
        {
         //...
        }
    }
}

关于c# - SingleOrDefault()似乎正在抛出System.NullReferenceException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33525186/

10-10 00:07