SingleOrDefault()似乎抛出了System.NullReferenceException

时间:2015-11-04 15:06:09

标签: c# asp.net linq

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

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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

说明

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

你没有通过辩论。但是,您在其中一个迭代中调用方法的对象为null。 (_ dataContext.ServiceJobs不包含服务作业ID 22)

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

祝你好运, 劳伦特

答案 2 :(得分:0)

只要“尝试取消引用空对象引用”(根据MSDN https://msdn.microsoft.com/en-us/library/vstudio/system.nullreferenceexception%28v=vs.110%29.aspx),就可以抛出NullReferenceException。这意味着任何尝试调用null对象上的方法或属性的代码都会抛出此execption。

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

相关问题