C#使用存储过程:我如何使用.FirstOrDefault()?

时间:2017-10-19 09:18:15

标签: c# sql sql-server

我编写了两个函数,函数#1从数据库中获取基于键的数据,函数#2调用第一个函数(如果存在数据),然后删除记录。

但是当数据不可用时,它也会输入if条件

public Employee GetEmployee(int Key)
{
      Employee employee = new Employee();

      if (con.State != System.Data.ConnectionState.Open)
      {
          con.Open();
      }

      SqlCommand cmd = new SqlCommand("Sp_GetById", con);
      cmd.CommandType = CommandType.StoredProcedure;
      cmd.Parameters.AddWithValue("@EmpId", Key);

      SqlDataReader rdr = cmd.ExecuteReader();

      if (rdr.HasRows == true)
      {
          while (rdr.Read())
          {
              employee.Emp_Id = Convert.ToInt32(rdr["Emp_Id"]);
              employee.EmpName = rdr[("EmpName")].ToString();

              if (!Convert.IsDBNull(rdr[("Cnt_Id")]))
              {
                  employee.Cnt_Id = Convert.ToInt32(rdr["Cnt_Id"]);
              }

我在GetEmployee()

中呼叫DeleteById(int key)
public void DeleteById(int Id)
{
     var x = GetEmployee(Id);

     if (x != null)
     {
     }
}

问题是当数据库中没有id时,代码仍然会进入If条件

3 个答案:

答案 0 :(得分:2)

在你获得功能中你有这个:

Employee employee = new Employee();

我假设在函数的最后你有类似的东西

return employee;

这就是为什么x永远不会为空。 你可以做一个

if(x.Id != null)

因为当db中没有emplyee时,id永远不会获得值。

答案 1 :(得分:1)

因为它在你的代码中不会为空,所以在GetEmployee内执行以下操作:

public Employee GetEmployee(int Key)
{
      //Employee employee = new Employee();//this will make the condition always true
      Employee employee = null;//Replace it with this to start with null value
      if (con.State != System.Data.ConnectionState.Open)
      {
          con.Open();
      }

然后在while里面会是这样的:

 while (rdr.Read())
 {
   employee = new Employee();//add this 
   employee.Emp_Id = Convert.ToInt32(rdr["Emp_Id"]);

答案 2 :(得分:0)

如果没有记录,则需要从" GetEmployee()"中返回null。方法。为此你可以做到这一点..

回答1)

      List<Employee> employee = new List<Employee>();
      SqlCommand cmd = new SqlCommand("Sp_GetById", con);
      cmd.CommandType = CommandType.StoredProcedure;
      cmd.Parameters.AddWithValue("@EmpId", Key);

      SqlDataReader rdr = cmd.ExecuteReader();

      if (rdr.HasRows == true)
      {
        while (rdr.Read())
        {
        employee.Add(new Employee{
        Emp_Id = Convert.ToInt32(rdr["Emp_Id"]),
        EmpName = rdr[("EmpName")].ToString()
           });
        }
     }

然后回来写这个..

return employee.FirstOrDefault();

如果有数据,FirstOrDefault()方法将返回单个Employee对象,否则返回null ...

回答2)

  Employee employee = new Employee();
  SqlCommand cmd = new SqlCommand("Sp_GetById", con);
  cmd.CommandType = CommandType.StoredProcedure;
  cmd.Parameters.AddWithValue("@EmpId", Key);

  SqlDataReader rdr = cmd.ExecuteReader();

  if (rdr.HasRows == true)
  {
    while (rdr.Read())
    {
       employee.Emp_Id = Convert.ToInt32(rdr["Emp_Id"]);
       employee.EmpName = rdr[("EmpName")].ToString();
    }
 }
 else
 {
   return null;
 }

return employee;
相关问题