尝试以c#形式从存储过程中查找必须返回值的值

时间:2014-02-19 14:25:37

标签: c# sql stored-procedures if-statement return-value

我在SQL中有一个存储过程,编码:

SELECT TOP 1 Intrecno FROM MainCallProblems 
ORDER BY Intrecno DESC

我在C#代码中使用:

long oldVal = ExecuteDataReader<MainCallProblems>("spGetMainCallProblemRefNo", null, typeof(MainCallProblems));.First().Intrecno;

请注意,数据库中的字段Intrecno是我的主键,bigint是一个标识(1,1)。

这用于返回值的服务。现在,表中没有任何内容可以调用,没有数据。

那么如何判断是否没有数据呢?返回值(也是SQL表中的类型)是一个长变量\ bigint

我试过了:

long newVal = 0;
        long oldVal = 0;
        // Generates list to see if there is anything stored within. If not, makes the first value 1
        List<MainCallProblems> mainCallProblemsList = ExecuteDataReader<MainCallProblems>("spGetMainCallProblemRefNo", null, typeof(MainCallProblems));
        if (mainCallProblemsList != null)
        {
            oldVal = mainCallProblemsList.First().Intrecno;
            newVal = oldVal + 1;
        }           
        else
        {
            newVal = 1;
        }
        return newVal;

这应该是看表中是否有任何内容。如果没有,返回是一个简单的1.如果有,则加载,更改和返回数据。 但是我在运行时遇到错误:

  

Reason =“System.InvalidOperationException:Sequence在CollectionMainCallProblemRefNoResponse

不要担心完整的错误。只要知道表中没有任何内容,它将作为错误返回。它甚至没有通过if语句来分配数据。

如何在不手动添加表格中的默认行的情况下纠正此错误。 IE:

insert into MainCallProblems(Assistant)
values('Joe')

2 个答案:

答案 0 :(得分:1)

您收到该错误是因为mainCallProblemsList不是null ...但 为空。并且First()要求集合中至少有一个项目。

改为使用Any

if (mainCallProblemsList.Any())
{
    oldVal = mainCallProblemsList.First().Intrecno;
    newVal = oldVal + 1;
}           
else
{
    newVal = 1;
}

答案 1 :(得分:0)

我会再增加一个条件,如下面的

if (mainCallProblemsList != null && mainCallProblemsList.Count > 0)