1

我有一个基于 Intranet Web 的应用程序,它将添加的用户的信息存储在其数据库中。

我想要做的是:当用户浏览到网站时,它会检查用户是否存在于自己的数据库中。如果没有,它将使用 Active Directory 检查他的信息。

我写了方法,但是在检查数据库后出现问题,如果用户不在那里,它将转到第二种方法,即检查员工的组织代码:

public static bool isMember(string userid)
{
        Employee employee = new Employee(userid);

        if (!String.IsNullOrEmpty(userid))
        {
            string username = userid;
            string connString = "Data Source=appServer\\sqlexpress;Initial Catalog=dbTest;Integrated Security=True";
            string cmdText2 = "SELECT Count(*) FROM employee WHERE Username = @username";

            using (SqlConnection conn = new SqlConnection(connString))
            {
                conn.Open();
                // Open DB connection.
                using (SqlCommand cmd = new SqlCommand(cmdText2, conn))
                {
                    cmd.Parameters.Add("@Username", SqlDbType.VarChar);
                    cmd.Parameters["@username"].Value = username;
                    var count = (int)cmd.ExecuteScalar();
                    return count == 1; // return true if there's only one employee with given name
                }
            }
        }
        else if (employee.department.Code == "30003143") //The SapCode of department is "30003143"
            return true;
        else
            return false;
    }

那么如何解决呢?如果数据库中不存在用户,如何使应用程序通过 (else if) 子句?

4

1 回答 1

1

挺容易:

public static bool isMember(string userid)
{
    // guard clause - if "userid" is invalid, return "false" right away 
    if (String.IsNullOrEmpty(userid))
    {
        return false
    }

    //Object from Employee class
    Employee employee = new Employee(userid);

    string username = userid;
    string connString = "Data Source=appServer\\sqlexpress;Initial Catalog=dbTest;Integrated Security=True";
    string cmdText2 = "SELECT Count(*) FROM employee WHERE Username = @username";

    using (SqlConnection conn = new SqlConnection(connString))
    using (SqlCommand cmd = new SqlCommand(cmdText2, conn))
    {
            cmd.Parameters.Add("@Username", SqlDbType.VarChar);
            cmd.Parameters["@username"].Value = username;

            conn.Open();

            var count = (int)cmd.ExecuteScalar();

            if (count == 1)
            {
               return true; // return true if there's only one employee with given name
            }
    }

    // if the user already existed in the database - then the above RETURN has 
    // returned "true" to the caller. So these lines are **only** executed if the
    // user was NOT found in the database.

    if (employee.department.Code == "30003143") //The SapCode of department is "30003143"
        return true;

    // now check in Active Directory here.....     
    return UserExistsInActiveDirectory();
}
于 2012-12-08T12:27:24.557 回答