1

我有一个 SQL 模板方法,我想返回一个字符串,以及各种执行查询的方法,我想从中获取字符串:

private string sqlQueryReturnString(Action<SqlConnection> sqlMethod)
{
    string result = "";
    SqlConnection conn = new SqlConnection();
    conn.ConnectionString = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
    try
    {
        //open SQL connection
        conn.Open();
        result = sqlMethod(conn);
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.Write(ex.ToString());
    }
    finally
    {
        conn.Close();
    }
    return result;
}

//Get the primary key of the currently logged in user
private string getPKofUserLoggedIn(SqlConnection conn)
{
    int result = 0;
    SqlCommand getPKofUserLoggedIn = new SqlCommand("SELECT [PK_User] FROM [User] WHERE [LoginName] = @userIdParam", conn);
    //create and assign parameters
    getPKofUserLoggedIn.Parameters.AddWithValue("@userIdParam", User.Identity.Name);
    //execute command and retrieve primary key from the above insert and assign to variable
    result = (int)getPKofUserLoggedIn.ExecuteScalar();
    return result.ToString();
}

以上是我认为的处理方式。这将是电话:

string test = sqlQueryReturnString(getPKofUserLoggedIn);

这部分不起作用:

result = sqlMethod(conn);

似乎 sqlMethod 被假定为无效。

我该怎么做才能获得我想要的功能?

4

1 回答 1

5

你想要一个Func<SqlConnection, string>. Action用于void方法,Func用于返回某些东西的方法。

于 2013-07-18T15:37:36.967 回答