public bool CheckTheEmail(string email)
{
//using (SqlConnection con = new SqlConnection("insQuoteConnectionString"))
using (SqlConnection con = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["insQuoteConnectionString"].ConnectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("select EmailAddress from AspNetUsers", con))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader != null)
{
while (reader.Read())
{
//do something
if (reader[0] != null)
{
if (reader[0] == (email))
{
Console.WriteLine("ok");
reader.Close();
con.Close();
return true;
}
}
}
}
reader.Close();
}
}
con.Close();
}
return false;
}
这句话如果(reader [0] ==(email))显示为true但不执行代码!
if语句返回true(在屏幕截图中显示)但不执行。
答案 0 :(得分:3)
每当您对某些内容进行比较时,确保他们使用兼容类型是一种很好的做法。在这种情况下,SqlDataReader
实际上返回Object
,因此您需要在进行比较之前将其强制转换为string
。 (我真的很惊讶IntelliSense并没有抱怨它)
public bool CheckTheEmail(string email)
{
using (SqlConnection con = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["insQuoteConnectionString"].ConnectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("select EmailAddress from AspNetUsers", con))
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader == default(SqlDataReader))
{
return false;
}
while (reader.Read())
{
//do something
if (reader[0] != null && reader[0].ToString() == email)
{
Console.WriteLine("ok");
return true;
}
}
}
}
return false;
}