C# 我的方法中存在Null引用异常。如何修复它?

C# 我的方法中存在Null引用异常。如何修复它?,c#,sql-server,ado.net,C#,Sql Server,Ado.net,这是我的密码。我认为问题在于我的声明@EmployeeId string strCommand = "insert into Employee (FirstName, LastName, Birthday, Inn)" + " values (@FirstName, @LastName, @Birthday, @Inn)" + " declare @EmployeeI

这是我的密码。我认为问题在于我的
声明@EmployeeId

string strCommand = "insert into Employee (FirstName, LastName, Birthday, Inn)" +
                    " values (@FirstName, @LastName, @Birthday, @Inn)" +
                    " declare @EmployeeId int = @@identity";

SqlCommand command = new SqlCommand(strCommand, connection);

command.Parameters.AddWithValue("@FirstName", employee.FirstName);
command.Parameters.AddWithValue("@LastName", employee.LastName);
command.Parameters.AddWithValue("@Birthday", employee.Birthday);
command.Parameters.AddWithValue("@Inn", employee.INN);

SqlParameter parameter = new SqlParameter("@EmployeeId", System.Data.SqlDbType.Int);
parameter.Direction = System.Data.ParameterDirection.Output;
//command.Parameters.Add(parameter); //???

try
{
    connection.Open();
    command.ExecuteNonQuery();

    employee.EmployeeId = (int)parameter.Value; // Here I get the exception
}
catch (Exception e)
{
    Console.WriteLine(e.Message);
    Console.WriteLine(e.StackTrace);
    // new Exception("Employee Not Insertes");
}
finally 
{
    connection.Close();
}

return employee;

这是唯一一种根本不起作用的方法。 对不起,我的英语不好。

我想这样做:

stringsql=”
插入员工(名、姓、生日、酒店)
输出inserted.Id——或者inserted.employeeid,如果这是列名的话
值(@FirstName、@LastName、@birth、@Inn);”;
//您应该为大多数查询创建一个新的连接对象。真正地
//阅读本文了解更多信息,了解原因:https://softwareengineering.stackexchange.com/q/142065/8057
//您还应该将该连接包装在using块中
使用(var connection=newsqlconnection(“此处为连接字符串”))
使用(var命令=新的SqlCommand(sql,连接))
{
//您应该避免AddWithValue()。在某些情况下,它可能会导致严重的性能损失
//相反,应该使用显式类型和长度
command.Parameters.Add(“@FirstName”,SqlDbType.NVarChar,15).Value=employee.FirstName;
command.Parameters.Add(“@LastName”,SqlDbType.NVarChar,20)。Value=employee.LastName;
command.Parameters.Add(“@birth”,SqlDbType.DateTime).Value=employee.birth);
command.Parameters.Add(“@Inn”,SqlDbType.Int).Value=employee.Inn;//不确定Inn代表什么。一些数字?
connection.Open();
employee.EmployeeId=(int)command.ExecuteScalar();
}
返回员工;

请注意,这允许我完全删除该行,但有一个例外。因此,它允许我在这里完全删除异常处理。相反,它可以移动到它所属的调用代码,因为关闭连接不再需要
finally
块。

我知道什么是空引用异常。我没有从parameter.value获得任何值。我认为我下面的代码中有一些错误。我没有回答我的问题。您也可以检查此问题:或此问题:
。Value
返回null,但代码试图将其转换为int
(int)null
无效。原因是SQL查询从不设置任何输出参数。事实上,没有输出参数,所有参数都是输入参数简而言之,
参数
从未收到值,因此
参数。值
为空现在我有System.InvalidCastException:“指定的强制转换无效。”employee.EmployeeId=(int)command.ExecuteScalar()旁边;Inn是number,但在我的程序中类型是string,所以我改为SqlDbType.NVarChar,20与您的C#程序类型无关。您希望它与数据库中的列匹配。但是对于特定错误,employee.EmployeeId看起来不是
int
。您可以通过更改强制转换来解决此问题,但更好的解决方法是更改Employee类以将该字段声明为int。问题不在Employeeid中,因为我甚至遇到了类似int b=(int)命令的问题。ExecuteScalar();command.ExecuteScalar()有问题;在数据库中,我用int表示EmployeeId。(int)command.ExecuteScalar()应该返回一个对象,但它会返回一个异常。Hmmm。。。我认为如果没有插入行,没有创建ID,这可能是可能的。在这种情况下,您将返回NULL或DBNull.Value,这不会转换为int。您应该使用调试器查看实际返回的内容。它返回一个异常。但是插入了一行。