使用 SqlDataReader 使条件正确?

Make condition right using SqlDataReader?

var a = "1";
var b = "2";
var c = "3";

var name = authResult.ExtraData["email"];

string connectionString = null;

SqlConnection cnn;
SqlCommand cmd;
string sql = null;
SqlDataReader reader;

connectionString = "Data Source = dj0043\sqlexpress; Initial Catalog = XXXX; Integrated Security = True";
sql = "Select EmployeeRoles.RoleId From EmployeeList Inner Join EmployeeRoles on EmployeeList.EmployeeId = EmployeeRoles.EmployeeId Where EmailId = name";

cnn = new SqlConnection(connectionString);

try
{
    cnn.Open();
    cmd = new SqlCommand(sql, cnn);
    reader = cmd.ExecuteReader();

    while (reader.Read())
    {
        if (reader == a)
        {
            return Redirect(Url.Action("Employee", "Home"));
        }
        else if (sql == b)
        {
            return Redirect(Url.Action("Index", "Home"));
        }
        else if (sql == c)
        {
            return Redirect(Url.Action("Index", "Home"));
        }
    }

    reader.Close();
    cmd.Dispose();
    cnn.Close();
}

在此,如果任何用户拥有 1 id 将被重定向到该页面,反之亦然。

谁能告诉我如何使 SqlDataReader 在这种情况下工作?

首先,您的SQL查询不正确。您应该将 @name 参数发送到查询中。

我更喜欢这样做,因为它更干净

var a = "1";
var b = "2";
var c = "3";

var name = authResult.ExtraData["email"];
var connectionString = "Data Source = dj0043\sqlexpress; Initial Catalog = XXXX; Integrated Security = True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
           connection.Open();
           using (SqlCommand cmd = connection.CreateCommand())
           {
               cmd.CommandText = "Select EmployeeRoles.RoleId From EmployeeList Inner Join EmployeeRoles on EmployeeList.EmployeeId = EmployeeRoles.EmployeeId Where EmailId = @name";
               cmd.CommandType = CommandType.Text;
               cmd.Parameters.Add("@name", SqlDbType.NVarChar).Value = name;


               using (SqlDataReader reader = cmd.ExecuteReader())
               {
                    while (reader.Read())
                    {
                       if (reader["RoleId"].ToString() == a)
                       {
                          return Redirect(Url.Action("Employee", "Home"));
                       }
                       else if (reader["RoleId"].ToString() == b)
                       {
                          return Redirect(Url.Action("Index", "Home"));
                       }
                       else if (reader["RoleId"].ToString() == c)
                       {
                          return Redirect(Url.Action("Index", "Home"));
                       }
                    }
               }
          }
}